您的位置:首页 > 编程语言 > C#

c#学习体会:使用 ref 和 out 传递数组(downmoon)

2007-12-28 14:20 453 查看
c#学习体会:使用 ref 和 out 传递数组(downmoon),希望与大家分享

1、与所有的 out 参数一样,在使用数组类型的 out 参数前必须先为其赋值,即必须由接受方为其赋值。例如:

public static void MyMethod(out int[] arr)

public static void MyMethod(ref int[] arr)

using System;

class TestOut

using System;

class TestRef

...{


public static void FillArray(ref int[] arr)




...{


// 根据需要创建一新的数组(不是必须的)


if (arr == null)


arr = new int[10];


// 否则填充数组,就可以了


arr[0] = 123;


arr[4] = 1024;


}




static public void Main ()




...{


//初始化数组:




int[] myArray = ...{1,2,3,4,5};




// 使用ref传递数组:


FillArray(ref myArray);




//显示更新后的数组元素:


Console.WriteLine("数组元素是:");


for (int i = 0; i < myArray.Length; i++)


Console.WriteLine(myArray[i]);


}


}

输出

数组元素是:

123

2

3

4

1024
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: