使用 ref 和 out 传递数组

本文通过两个示例对比介绍了C#中ref与out参数的使用方式。第一个示例展示了如何使用out参数初始化并返回一个数组;第二个示例则演示了如何使用ref参数修改传入的数组。
与所有的out 参数一样,在使用数组类型的ref 参数前必须先为其赋值,即必须由被调用方为其赋值。
ContractedBlock.gifExpandedBlockStart.gif程序如下:
 1在此例中,在调用(Main 方法)中声明数组 theArray,并在 FillArray 方法中初始化此数组。然后将数组元素返回调用方并显示。
 2class TestOut
 3ExpandedBlockStart.gifContractedBlock.gif{
 4    static void FillArray(out int[] arr)
 5ExpandedSubBlockStart.gifContractedSubBlock.gif    {
 6        // Initialize the array:
 7ExpandedSubBlockStart.gifContractedSubBlock.gif        arr = new int[512345 };
 8    }

 9
10    static void Main()
11ExpandedSubBlockStart.gifContractedSubBlock.gif    {
12        int[] theArray; // Initialization is not required
13
14        // Pass the array to the callee using out:
15        FillArray(out theArray);
16
17        // Display the array elements:
18        System.Console.WriteLine("Array elements are:");
19        for (int i = 0; i < theArray.Length; i++)
20ExpandedSubBlockStart.gifContractedSubBlock.gif        {
21            System.Console.Write(theArray[i] + " ");
22        }

23    }

24}
程序输出结果如下:
25Array elements are: 
26
271 2 3 4 5 
28在此例中,在调用(Main 方法)中初始化数组 theArray,并通过使用 ref 参数将其传递给 FillArray 方法。在 FillArray 方法中更新某些数组元素。然后将数组元素返回调用方并显示。
29class TestRef
30ExpandedBlockStart.gifContractedBlock.gif{
31    static void FillArray(ref int[] arr)
32ExpandedSubBlockStart.gifContractedSubBlock.gif    {
33        // Create the array on demand:
34        if (arr == null)
35ExpandedSubBlockStart.gifContractedSubBlock.gif        {
36            arr = new int[10];
37        }

38        // Fill the array:
39        arr[0= 1111;
40        arr[4= 5555;
41    }

42
43    static void Main()
44ExpandedSubBlockStart.gifContractedSubBlock.gif    {
45        // Initialize the array:
46ExpandedSubBlockStart.gifContractedSubBlock.gif        int[] theArray = 12345 };
47
48        // Pass the array using ref:
49        FillArray(ref theArray);
50
51        // Display the updated array:
52        System.Console.WriteLine("Array elements are:");
53        for (int i = 0; i < theArray.Length; i++)
54ExpandedSubBlockStart.gifContractedSubBlock.gif        {
55            System.Console.Write(theArray[i] + " ");
56        }

57    }

58}

59程序输出结果如下:
60Array elements are: 
61
621111 2 3 4 5555 
63

转载于:https://www.cnblogs.com/epwqgdnvrhok/archive/2008/12/20/1358924.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值