c# ---使用 ref 和 out 传递数组
来源:互联网 发布:股票走势预测 python 编辑:程序博客网 时间:2024/05/21 14:43
与所有的 out 参数一样,在使用数组类型的 out 参数前必须先为其赋值,即必须由被调用方为其赋值。例如:
C#
复制
static void TestMethod1(out int[] arr){ arr = new int[10]; // definite assignment of arr}
与所有的 ref 参数一样,数组类型的 ref 参数必须由调用方明确赋值。因此不需要由接受方明确赋值。 可以将数组类型的 ref 参数更改为调用的结果。 例如,可以为数组赋以 null 值,或将其初始化为另一个数组。例如:
C#
复制
static void TestMethod2(ref int[] arr){ arr = new int[10]; // arr initialized to a different array}
下面的两个示例说明 out 与ref 在将数组传递给方法时的用法差异。
示例
在此例中,在调用方(Main 方法)中声明数组theArray,并在 FillArray 方法中初始化此数组。然后将数组元素返回调用方并显示。
C#
复制
class TestOut{ static void FillArray(out int[] arr) { // Initialize the array: arr = new int[5] { 1, 2, 3, 4, 5 }; } static void Main() { int[] theArray; // Initialization is not required // Pass the array to the callee using out: FillArray(out theArray); // Display the array elements: System.Console.WriteLine("Array elements are:"); for (int i = 0; i < theArray.Length; i++) { System.Console.Write(theArray[i] + " "); } // Keep the console window open in debug mode. System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); }} /* Output: Array elements are: 1 2 3 4 5 */
在此例中,在调用方(Main 方法)中初始化数组theArray,并通过使用 ref 参数将其传递给FillArray 方法。 在FillArray 方法中更新某些数组元素。 然后将数组元素返回调用方并显示。
C#
复制
class TestRef{ static void FillArray(ref int[] arr) { // Create the array on demand: if (arr == null) { arr = new int[10]; } // Fill the array: arr[0] = 1111; arr[4] = 5555; } static void Main() { // Initialize the array: int[] theArray = { 1, 2, 3, 4, 5 }; // Pass the array using ref: FillArray(ref theArray); // Display the updated array: System.Console.WriteLine("Array elements are:"); for (int i = 0; i < theArray.Length; i++) { System.Console.Write(theArray[i] + " "); } // Keep the console window open in debug mode. System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); }} /* Output: Array elements are: 1111 2 3 4 5555 */
- c#使用 ref 和 out 传递数组
- c# ---使用 ref 和 out 传递数组
- c#学习体会:使用 ref 和 out 传递数组(downmoon)
- C#中使用 ref 和 out 传递数组
- c#学习体会:使用 ref 和 out 传递数组
- c#学习体会:使用 ref 和 out 传递数组(downmoon)
- c#学习体会:使用 ref 和 out 传递数组(downmoon)
- C#中使用ref和out传递数组的方法
- c#学习体会:使用 ref 和 out 传递数组(downmoon)
- 使用 ref 和 out 传递数组(C# 编程指南)
- 使用 ref 和 out 传递数组
- c#:使用 ref 和 out 传递数组
- 使用 ref 和 out 传递数组
- 使用 ref 和 out 传递数组
- 使用 ref 和 out 传递数组
- 使用 ref 和 out 传递数组
- 使用 ref 和 out 传递数组
- C#方法参数传递-同时使用ref和out关键字
- mit 计算机科学及编程导论(3)
- 每天一点正则表达式积累(三)
- 对UIView设置Shadow,Border,Radius
- 结构体对齐的具体含义
- lua笔记之函数(2)
- c# ---使用 ref 和 out 传递数组
- 运行python manage.py runserver报错现象、原因和解决办法
- Linux/shell命令的实际应用——wc命令获取CPU核心数
- iOS开发19:Navigation Bar的简单设置
- 做推箱子小游戏的一些总结
- 谈谈Objective-C中@class的作用和用法
- struts2学习笔记
- dbcontrol console 创建注意事项
- 静观其变