C#中ref和out的区别

C#中的ref和out提供了值类型按引用进行传递的解决方案,当然引用类型也可以用ref和out修饰,但这样已经失去了意义。因为引用数据类型本来就是传递的引用本身而非值的拷贝。ref和out关键字将告诉编译器,现在传递的是参数的地址而不是参数本身,这和引用类型默认的传递方式是一样的。
ref和out的区别:
1、重载:out和ref不能构成重载,编译器提示:不能定义仅在ref和out的上存在不同的重载方法
eg、

		static void Fun(ref int a,ref int b)
    	{
       		 a = a + b;
        	 b = 6;
    	}
    	static void Fun(out int a,out int b)
    	{
       		 b = 6;
        	 a = 14;
    	}

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

3、函数中,参数赋值
在调用函数中,out引入的参数必须赋值;
而ref引入的参数在返回前可以不赋值;

比较完整的测试代码:

class Program
{
   static void Main(string[] args)
    {
        int a = 6;
        int b = 66;
        Fun(ref a,ref b);
         //Fun(out a,out b);
        Console.WriteLine("a:{0},b:{1}",a,b);
        Console.ReadLine();

    }
  static void Fun(ref int a,ref int b)
    {
        a = a + b;
       // b = 6;
    }

 	  /*
   static void Fun(out int a,out int b)
    {
        b = 6;
        a = 14;
    }*/
}

猜你喜欢

转载自blog.csdn.net/qq_43026206/article/details/84065502