ref和out共同点和区别

ref:

引用传递,从外部传递地址进方法
下面展示一些 内联代码片

//ref的创建和调用
public void getValuse(ref int x,ref double y,ref string z)
        {
    
    
            Console.WriteLine("请输入年龄: ");
            x = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("请输入身高: ");
            y = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("请输入姓名: ");
            z = Convert.ToString(Console.ReadLine());
            
        }
         static void Main(string[] args)
        {
    
    
        	int d = 0;
            double n =0d;
            string l = null;
            Program k = new Program();
            k.getValuse(ref d,ref n,ref l);
            Console.WriteLine("请输入姓名:{0}", d);
            Console.WriteLine("请输入年龄:{0}岁",n);
            Console.WriteLine("请输入身高:{0}cm", l);
            Console.ReadLine();
            }
请输入年龄:
20
请输入身高:
180
请输入姓名:
阿斯顿
请输入姓名:阿斯顿
请输入年龄:20岁
请输入身高:180cm

out:通过引用而不通过值传递参数,在方法内部做分配地址后,把地址赋给外部变量

下面展示一些 内联代码片

// An highlighted block
public void getValuse1(out int x, out double y, out string z)
        {
    
    
            Console.WriteLine("请输入年龄: ");
            x = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("请输入身高: ");
            y = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("请输入姓名: ");
            z = Convert.ToString(Console.ReadLine());

        }
        static void Main(string[] args)
        {
    
    
            int d ;
            double n ;
            string l ;
            Program k = new Program();
            k.getValuse1(out d, out n, out l);
             Console.WriteLine("请输入姓名:{0}", d);
            Console.WriteLine("请输入年龄:{0}岁",n);
            Console.WriteLine("请输入身高:{0}cm", l);
            Console.ReadLine();
            }
请输入年龄:
20
请输入身高:
180
请输入姓名:
阿斯顿
请输入姓名:阿斯顿
请输入年龄:20岁
请输入身高:180cm

大家可以看到二者输出的结果相同,但还是有区别的

ref和out的区别

  1. ref 型传递变量前,变量必须初始化,否则编译器会报错, 而 out 型则不需要初始化
  2. ref不需要,而out指定的参数进入方法时会清空自己,必须在方法内部赋初始值
  3. ref有进有出,out只出不进

注意:

out型数据在方法中必须要赋值,否则编译器会报错
重载方法时若两个方法的区别仅限于一个参数类型为ref 另一个方法中为out,编译器会报错

猜你喜欢

转载自blog.csdn.net/m0_47605113/article/details/108615089