有关C#中的引用类型的内存问题

对于一个类,如果定义后(记作对象a),将另外一个对象b直接赋值(“a = b”)给它,则相当于将地址赋值给了这个对象。当另外一个对象b不再对这块地址应用时,a由于对这块地址仍在使用,这块地址的指向的栈空间仍然不被销毁。直道没有对象再对其引用,系统将按照回收机制对其进行回收。

Demo如下:

 public class ObjectRef
    {
        public static void Demo_Main()
        {
            PointD a, b, c;

            b = new PointD(100, 58);
            a = b;
            b = new PointD(200, 11);
           

            Console.WriteLine("a is now {0}, {1}", a.X, a.Y); // a is now 100, 58
            c = new PointD(300, 22);
            a = c;
            c.X = 500;
            Console.WriteLine("a is now {0}, {1}", a.X, a.Y); // a is now 500, 22
        }
    }


    public class PointD
    {
        int x;
        int y;

        public int X
        {
            get { return x; }
            set { x = value; }
        }
        
        public int Y
        {
            get { return y; }
            set { y = value; }
        }

        public PointD(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }

猜你喜欢

转载自www.cnblogs.com/arxive/p/9242738.html