总结ref和out的区别

之前每次遇到ref和out时,老是忘记他们的使用方法和区别。每次都要网上搜一下别人写的博客来回忆。这次干脆自己整合一下别人博客的内容,方便下次忘记时查询。

用途:

 在C#中通过使用方法来获取返回值时,通常只能得到一个返回值。因此,当一个方法需要返回多个值的时候,就需要用到ref和out。

 

概述:

ref 关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。

out 关键字会导致参数通过引用来传递。这与 ref 关键字类似,不同之处在于 ref 要求变量必须在传递之前进行初始化。若要使用 out 参数,方法定义和调用方法都必须显式使用 out 关键字。 

 

同:

1、都能返回多个返回值。

2、若要使用 ref 和out参数,则方法定义和调用方法都必须显式使用 ref和out 关键字。在方法中对参数的设置和改变将会直接影响函数调用之处(参数的初始值)。

 

异:

1、ref指定的参数在函数调用时候必须初始化,不能为空的引用。而out指定的参数在函数调用时候可以不初始化;

2、out指定的参数在进入函数时会清空自己,必须在函数内部赋初值。而ref指定的参数不需要。

 

口诀:

ref有进有出,out只出不进。

正确的使用ref:

class Program
    {
        static void Main(string[] args)
        {
            Program pg = new Program();
            int x = 10;
            int y = 20;
            pg.GetValue(ref x, ref  y);
            Console.WriteLine("x={0},y={1}", x, y);
 
            Console.ReadLine();
        }
 
        public void GetValue(ref int x, ref int y)
        {
            x = 521;
            y = 520;
        }
    }

运行结果为 

x=521,y=520

错误的使用ref:

class Program
    {
        static void Main(string[] args)
        {
            Program pg = new Program();
            int x;
            int y;        //此处x,y没有进行初始化,则编译不通过。
            pg.GetValue(ref x, ref  y);
            Console.WriteLine("x={0},y={1}", x, y);
 
            Console.ReadLine();
        }
 
        public void GetValue(ref int x, ref int y)
        {
            x = 1000;
            y = 1;
        }    
    }

  

正确的使用out:

class Program
    {
        static void Main(string[] args)
        {
            Program pg = new Program();
            int x=10;
            int y=233;
            pg.Swap(out x, out y);
            Console.WriteLine("x={0},y={1}", x, y);
 
            Console.ReadLine();
        }
 
        public void Swap(out int a,out  int b)
        {
            int temp = a;   //a,b在函数内部没有赋初值,则出现错误。
            a = 521;
            b = 520;
        }     
    }

  

运行结果为 

x=521,y=520

错误的使用out:

class Program
    {
        static void Main(string[] args)
        {
            Program pg = new Program();
            int x=10;
            int y=233;
            pg.Swap(out x, out y);
            Console.WriteLine("x={0},y={1}", x, y);
 
            Console.ReadLine();
        }
 
        public void Swap(out int a,out  int b)
        {
            int temp = a;   //a,b在函数内部没有赋初值,则出现错误。
            a = b;
            b = temp;
        }     
    }

  

原文连接

https://www.cnblogs.com/wolf-sun/p/3371174.html

https://www.cnblogs.com/yanhan/archive/2013/01/26/2877889.html

posted on 2022-11-10 07:32  hushzhang  阅读(447)  评论(0编辑  收藏  举报

导航