C#中out和ref之间的区别

ref参数是引用,out参数为输出参数。

ref的使用:使用ref进行参数的传递时,该参数在创建时,必须设置其初始值,且ref侧重于修改;

out的使用: 采用out参数传递时,该参数在创建时,可以不设置初始值,但是在方法中必须初始化,out侧重于输出;

   public class Base
    {  
        public void outMethod(out string x)
        {
            x = "this is outMethod";
        } 
        public void refMethod(ref string x)
        {
            x = "this is refMethod";
        }
    }

  

        static void Main(string[] args)
        {
            
            Base ba = new Base();

            string i;//可以不初始化。因为out
            ba.outMethod(out i);
            Console.WriteLine(i);

            string j = "0";//必须初始化,因为ref
            ba.refMethod(ref j);
            Console.WriteLine(j); 
            Console.ReadLine();
        }

  

原文地址:https://www.cnblogs.com/lijianhong90/p/8481139.html