C#中out和ref使用

1、out必须在方法中为其赋值,在调用的时候必须在变量的前面加上out关键字,侧重输出。

2、ref修饰方法的参数,在调用的时候必须在变量的前面加上ref关键字,可以修改其值也可以不修改,侧重修改。

3、out和ref只能传递变量不能传常量,传递的时候不是传递变量的值,而是传变量的地址。

3、out在传递之前可以不赋初始值,因为在方法里面肯定会为out赋值,ref在传递之前必须要有值,因为在方法中有可能会用到参数的值。

static void TestOut(out int i)

{

   i=110;//out中一定要对变量赋值

}

static void TestRef(ref int i)

{

  i+=1;//ref中可以对变量赋值也可以不赋值

}

staitc void Main(string[] args)

{

   int i=12;

   TestOut(out i);

   //TestOut(out 12);这样就报错,只能传变量不能传常量

   Console.WriteLine(i);

   int[] arr={1,2,4,6,3};

   int min=0;

   int max=0;

   GetMaxAndMin(arr,out max,out min);

   Console.WriteLine(min+":"+max);

   int num;

   //TestRef(ref num);//这样就有可能报错,因为方法中可能会用到参数的值,而在ref里面没有对变量赋值。

   //TestOut(out num);//这样不会报错,因为out里面一定会对变量赋值。

   //Console.WriteLine(num);

}

static void GetMaxAndMin(int[] arr,out int max,out int min)

{

    //排序 Array.Sort(arr);

    //冒泡排序

    for(int i=0;i<arr.Length-1;i++)

    {

       for(int j=0;j<arr.Length-1-i;j++)

       {

          if(arr[j]>arr[j+1])

          {

               int temp=arr[j];

               arr[j]=arr[j+1];

               arr[j+1]=temp;

          }

       }
    }

    max=arr[arr.Length-1];

    min=arr[0];

}
View Code

附图(理解out和ref只是传递的地址而不是值):

注:以上内容均属软谋原创,转载请注明出处。

原文地址:https://www.cnblogs.com/ruanmou001/p/3301273.html