ref & out - C#中的参数传递

  ref与out均指定函数参数按引用传递,惟一的不同是,ref传递的参数必须初始化,而out可以不用。

  ref与out无法作为重载的依据,即ref与out编译器认为一样。如下:

  ref & out - C#中的参数传递

  但是ref函数与非ref函数是可以重载的,如下:

  ref & out - C#中的参数传递

  To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword, as shown in the following example.

  ref & out - C#中的参数传递

  A variable of a reference type does not contain its data directly; it contains a reference to its data. out keyword.

class PassingRefByVal 
{
    static void Change(int[] pArray)
    {
        pArray[0] = 888;  // This change affects the original element.
        pArray = new int[5] {-3, -1, -2, -3, -4};   // This change is local.
        System.Console.WriteLine("Inside the method, the first element is: {0}", pArray[0]);
    }

    static void Main() 
    {
        int[] arr = {1, 4, 5};
        System.Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", arr [0]);

        Change(arr);
        System.Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", arr [0]);
    }
}
/* Output:
    Inside Main, before calling the method, the first element is: 1
    Inside the method, the first element is: -3
    Inside Main, after calling the method, the first element is: 888
*/
View Code

相关文章:

  • 2021-11-18
  • 2022-01-13
  • 2022-12-23
  • 2021-10-30
  • 2021-08-29
  • 2022-12-23
  • 2022-12-23
  • 2018-09-03
猜你喜欢
  • 2021-05-23
  • 2021-08-31
  • 2021-12-02
  • 2021-05-28
  • 2022-12-23
  • 2022-12-23
  • 2021-08-19
相关资源
相似解决方案