zoukankan      html  css  js  c++  java
  • 使用 ref 和 out 传递数组

    与所有的 out 参数一样,在使用数组类型的 out 参数前必须先为其赋值,即必须由接受方为其赋值。例如:
    public static void MyMethod(out int[] arr)
    {
       arr = new int[10];   // definite assignment of arr
    }
    与所有的 ref 参数一样,数组类型的 ref 参数必须由调用方明确赋值。因此不需要由接受方明确赋值。可以将数组类型的 ref 参数更改为调用的结果。例如,可以为数组赋以 null 值,或将其初始化为另一个数组。例如:
    public static void MyMethod(ref int[] arr)
    {
       arr = new int[10];   // arr initialized to a different array
    }
    下面的两个示例说明 out 和 ref 在将数组传递给方法上的用法差异。
    示例 1
    在此例中,在调用方(Main 方法)中声明数组 myArray,并在 FillArray 方法中初始化此数组。然后将数组元素返回调用方并显示。
    // cs_array_ref_and_out.cs
    using System;
    class TestOut
    {
       static public void FillArray(out int[] myArray)
       {
          // Initialize the array:
          myArray = new int[5] {1, 2, 3, 4, 5};
       }

       static public void Main()
       {
          int[] myArray; // Initialization is not required

          // Pass the array to the callee using out:
          FillArray(out myArray);

          // Display the array elements:
          Console.WriteLine("Array elements are:");
          for (int i=0; i < myArray.Length; i++)
             Console.WriteLine(myArray[i]);
       }
    }
    输出
    Array elements are:
    1
    2
    3
    4
    5
    示例 2
    在此例中,在调用方(Main 方法)中初始化数组 myArray,并通过使用 ref 参数将其传递给 FillArray 方法。在 FillArray 方法中更新某些数组元素。然后将数组元素返回调用方并显示。
    // cs_array_ref_and_out2.cs
    using System;
    class TestRef
    {
       public static void FillArray(ref int[] arr)
       {
          // Create the array on demand:
          if (arr == null)
             arr = new int[10];
          // Otherwise fill the array:
          arr[0] = 123;
          arr[4] = 1024;
       }

       static public void Main ()
       {
          // Initialize the array:
          int[] myArray = {1,2,3,4,5}; 

          // Pass the array using ref:
          FillArray(ref myArray);

          // Display the updated array:
          Console.WriteLine("Array elements are:");
          for (int i = 0; i < myArray.Length; i++)
             Console.WriteLine(myArray[i]);
       }
    }
    输出
    Array elements are:
    123
    2
    3
    4
    1024

  • 相关阅读:
    jQuery中.html(“xxx”)和.append("xxx")的区别和不同
    Jquery中对checkbox的各种“全选”或者“取消”功能实现(特别注意1.6+的一定不能使用attr来取属性了!用prop!)
    Jquery 中each循环嵌套的使用示例教程
    关于Jquery中的$.each获取各种返回类型数据的使用方法
    IMEI是什么? 怎样查手机串号IMEI
    linux useradd(adduser)命令参数及用法详解(linux创建新用户命令)
    linux 的useradd 命令的p选项
    Linux SSH远程文件/目录传输命令scp
    C++ 迭代器 基础介绍
    C++中map的一点疑惑...
  • 原文地址:https://www.cnblogs.com/yitian/p/1383584.html
Copyright © 2011-2022 走看看