Csharp-output-parameters
提供:Dev Guides
C#-出力によるパラメーターの受け渡し
returnステートメントは、関数から1つの値のみを返すために使用できます。 ただし、*出力パラメーター*を使用すると、関数から2つの値を返すことができます。 出力パラメーターは参照パラメーターに似ていますが、データをメソッドではなくメソッドから転送する点が異なります。
次の例はこれを示しています-
using System;
namespace CalculatorApplication {
class NumberManipulator {
public void getValue(out int x ) {
int temp = 5;
x = temp;
}
static void Main(string[] args) {
NumberManipulator n = new NumberManipulator();
/*local variable definition*/
int a = 100;
Console.WriteLine("Before method call, value of a : {0}", a);
/*calling a function to get the value*/
n.getValue(out a);
Console.WriteLine("After method call, value of a : {0}", a);
Console.ReadLine();
}
}
}
上記のコードをコンパイルして実行すると、次の結果が生成されます-
Before method call, value of a : 100
After method call, value of a : 5
出力パラメーターに指定された変数に値を割り当てる必要はありません。 出力パラメーターは、パラメーターに初期値を割り当てずにパラメーターからメソッドから値を返す必要がある場合に特に役立ちます。 これを理解するために、次の例をご覧ください-
using System;
namespace CalculatorApplication {
class NumberManipulator {
public void getValues(out int x, out int y ) {
Console.WriteLine("Enter the first value: ");
x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second value: ");
y = Convert.ToInt32(Console.ReadLine());
}
static void Main(string[] args) {
NumberManipulator n = new NumberManipulator();
/*local variable definition*/
int a , b;
/*calling a function to get the values*/
n.getValues(out a, out b);
Console.WriteLine("After method call, value of a : {0}", a);
Console.WriteLine("After method call, value of b : {0}", b);
Console.ReadLine();
}
}
}
上記のコードをコンパイルして実行すると、次の結果が生成されます-
Enter the first value:
7
Enter the second value:
8
After method call, value of a : 7
After method call, value of b : 8