纸上得来终觉浅,绝知此事要躬行。

 

ref和out的使用方法

out 关键字会导致参数通过引用来传递。这与ref关键字类似,不同之处在于ref要求变量必须在传递之前进行初始化。若要使用 out 参数,
方法定义和调用方法都必须显式使用 out 关键字。例如:
1 class OutExample
2 {
3 static void Method(out int i)
4 {
5 i = 44;
6 }
7 static void Main()
8 {
9 int value;
10 Method(out value);
11 // value is now 44
12   }
13 }

 

在此例中,在调用方(Main 方法)中声明数组 theArray,并在 FillArray 方法中初始化此数组。然后将数组元素返回调用方并显示.
1 class TestOut
2 {
3 static void FillArray(out int[] arr)
4 {
5 // Initialize the array:
6   arr = new int[5] { 1, 2, 3, 4, 5 };
7 }
8
9 static void Main()
10 {
11 int[] theArray; // Initialization is not required
12
13 // Pass the array to the callee using out:
14   FillArray(out theArray);
15
16 // Display the array elements:
17   System.Console.WriteLine("Array elements are:");
18 for (int i = 0; i < theArray.Length; i++)
19 {
20 System.Console.Write(theArray[i] + " ");
21 }
22 }
23 }

结果为:1,2,3,4,5

与所有的 ref 参数一样,数组类型的 ref 参数必须由调用方明确赋值。因此不需要由接受方明确赋值。可以将数组类型的 ref 参数更改为调用的结果。例如,可以为数组赋以 null值,或将其初始化为另一个数组。

例如:  

1 static void TestMethod2(ref int[] arr)
2 {
3 arr = new int[10]; // arr initialized to a different array
4  }

在此例中,在调用方(Main 方法)中初始化数组 theArray,并通过使用 ref 参数将其传递给 FillArray 方法。在 FillArray方法中更新某些数组元素。然后将数组元素返回调用方并显示。  

1 class TestRef
2 {
3 static void FillArray(ref int[] arr)
4 {
5 // Create the array on demand:
6   if (arr == null)
7 {
8 arr = new int[10];
9 }
10 // Fill the array:
11   arr[0] = 1111;
12 arr[4] = 5555;
13 }
14
15 static void Main()
16 {
17 // Initialize the array:
18   int[] theArray = { 1, 2, 3, 4, 5 };
19
20 // Pass the array using ref:
21   FillArray(ref theArray);
22
23 // Display the updated array:
24   System.Console.WriteLine("Array elements are:");
25 foreach(int sss in theArray)
26 {
27 System.Console.Write(sss);
28 }
29 }
30 }

结果:Array elements are:   1111  2  3  4  555

posted on 2010-07-14 18:25  JRoger  阅读(376)  评论(0编辑  收藏  举报

导航