C#Ref和Out作用于引用对象时的理解

class Program
    {
        static void Main(string[] args)
        {
            
            var a = new AAA() { aaa = 0 };
            test(a);

            Console.WriteLine("无Ref:"+ a.aaa);
            testRef(ref a);

            Console.WriteLine("Ref:" +a.aaa);
        }
        public static void test(AAA a)
        {
            a.aaa = 1;
            var c = new AAA() { aaa = 2 };
            a = c;
        }
        public static void testRef(ref AAA a)
        {
            a.aaa = 1;
            var c = new AAA() { aaa = 2 };
            a = c;
        }
    }
    public class  AAA
    {
        public int aaa { get; set; }
    }

可以看到,当对引用类型加了ref关键字时,可以改变对象本身。不加ref则只能修改对象的成员。
即在方法内部对传入的参数本身重新赋值时。外部是不会受到影响的。不论传入的值类型还是引用类型。

原文地址:https://www.cnblogs.com/qwfy-y/p/14421758.html