Common and difference between ref and out

ref:

Pass by reference, pass the address from the outside into the method
Here are some 内联代码片.

//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: Pass parameters by reference instead of by value, after assigning the address inside the method, assign the address to the external variable

Show some below 内联代码片.

// 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

You can see that the output results of the two are the same, but there are still differences

The difference between ref and out

  1. The variable must be initialized before the ref type is passed, otherwise the compiler will report an error, while the out type does not need to be initialized
  2. ref does not need, and the parameter specified by out will clear itself when entering the method, and the initial value must be assigned inside the method
  3. ref is in and out, out is only out but not in

note:

The out type data must be assigned in the method, otherwise the compiler will report an error. When the
method is overloaded, if the difference between the two methods is limited to one parameter type being ref and the other method being out, the compiler will report an error

Guess you like

Origin blog.csdn.net/m0_47605113/article/details/108615089