サンプル集  >  C#  >  関数呼び出し
関数呼び出し
2017/09/11

関数内で引数の値を書き換える例です。

◆環境
OS Windows 7 Professional Service Pack 1 32bit
C# 2010 01018-587-4054026-70893

以下の手順を行います。

  1. [ファイル]-[新規作成]-[プロジェクト]を選択。
  2. [他の言語]-[Visual C#]-[コンソール アプリケーション]を選択。
  3. 名前に「FuncTest」と入力し「OK」ボタンを押下。

関数内で引数の変数の値を書き換えたい場合、参照渡しにする必要があります。 そのために ref キーワードを変数の前に指定します。

Program.cs
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
39: 
40: 
41: 
42: 
43: 
44: 
45: 
46: 
47: 
48: 
49: 
50: 
51: 
52: 
53: 
54: 
55: 
56: 
57: 
58: 
59: 
60: 
61: 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace funcTest
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 1;
            int b = 2;
            Console.WriteLine( "main:bfr:a=" + a
                                     + " b=" + b
                             );

            func1(a, ref b);
            Console.WriteLine( "main:aft:a=" + a
                                     + " b=" + b
                             );

            string c = "ABC";
            string d = "DEF";
            Console.WriteLine( "main:bfr:c=" + c
                                     + " d=" + d
                             );

            func2(c, ref d);
            Console.WriteLine( "main:aft:c=" + c
                                     + " d=" + d
                             );

            Console.Read();
        }

        static void func1(int a, ref int b)
        {
            Console.WriteLine("sub:bfr:a=" + a
                                   + " b=" + b
                             );
            a = 3;
            b = 4;
            Console.WriteLine("sub:aft:a=" + a
                                   + " b=" + b
                             );
        }

        static void func2(string c, ref string d)
        {
            Console.WriteLine("sub:bfr:c=" + c
                                   + " d=" + d
                             );
            c = "abc";
            d = "def";
            Console.WriteLine("sub:aft:c=" + c
                                   + " d=" + d
                             );
        }
    }
}

実行してみます。

main:bfr:a=1 b=2
sub:bfr:a=1 b=2
sub:aft:a=3 b=4
main:aft:a=1 b=4
main:bfr:c=ABC d=DEF
sub:bfr:c=ABC d=DEF
sub:aft:c=abc d=def
main:aft:c=ABC d=def

refを指定していない変数は、関数の中で値を変更しても呼び元には反映されません。

▲ PageTop  ■ Home


Copyright (C) 2017 ymlib.com