object类型对象 ref参数如何理解?

 class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student { Name = "老王" };
            test(ref stu);
            Console.WriteLine(stu.Name);
            Console.Read();
        }

        static void test(Student stu)
        {
            stu = new Student { Name="刘哥" };
            Console.WriteLine(stu.Name);
        }

        static void test(ref Student stu)
        {
            stu = new Student { Name = "刘哥" };
            Console.WriteLine(stu.Name);
        }
    }

    public class Student
    {
        public string Name { get; set; }
    }

不加ref 和加了ref 很明显结果是不一样的

如何理解加了和不加的区别

首先要知道构造一个对象的时候,内存中堆栈的分配情况,stu这个变量在栈中,而对象在堆中,变量中存放的是堆的地址。

因此如果不加ref,参数就是一个副本,存放的是堆中的地址。如果我们不改变地址,(也就是我们不去new一个对象对这个副本指向新的堆地址),其实是没有区别的,为什么?因为无论怎么操作,始终改变的是堆中的对象,如果我们new了一个新的对象,那么这个副本的地址发生变化了,但是stu这个变量指向的地址呢?依然没有发生变化。

因此如果加了ref呢?传递的是什么呢,是stu本身,并不是stu的副本,所以如果为stu重新new一个对象,那么它指向的地址自然就改变了。

原文地址:https://www.cnblogs.com/njcxwz/p/6533352.html