C#基础——值传递和引用传递

参考:https://blog.csdn.net/m0_37679113/article/details/83045813
ref作为参数的函数在调用前,实参必须赋初始值。

out作为参数的函数在调用前,实参可以不赋初始值。

ref可以把参数的数值传递进函数,但是out是要把参数清空,就是说你无法把一个数值从out传递进去的,out进去后,参数的数值为空,所以你必须初始化一次。这个就是两个的区别,或者说就像有的网友说的,ref是有进有出,out是只出不进。

class Program
{
   static void Main(string[] args)
    {
        int a = 6;
        int b = 66;
        Fun(ref a,ref b);

        Console.WriteLine("a:{0},b:{1}",a,b);
        Console.ReadLine();
    }
  static void Fun(ref int a,ref int b)
    {
        a = a + b;
    }
}
int number;

Method(out number);

void Method(out int myRefInt)
{
    myRefInt = 66;
}

Console.WriteLine(number);
//输出:66
posted @ 2020-07-03 12:17  LY-CS  阅读(202)  评论(0编辑  收藏  举报