码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2018-06-29 13:58:07      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:对象   赋值   family   return   this   bsp   void   span   his   

 

对于一个类,如果定义后(记作对象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;
        }
    }

 

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

标签:对象   赋值   family   return   this   bsp   void   span   his   

原文地址:https://www.cnblogs.com/arxive/p/9242738.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!