如何在C#中为引用类型分配内存?

Jeb*_*bli 1 .net c#

嗨,我对引用类型的内存分配有一些疑问.请澄清我在下面的代码之间评论的问题.

 class Program
    {
        static void Main(string[] args)
        {
            testclass objtestclass1 = new testclass();
            testclass objtestclass2 = new testclass();
            testclass objtestclass3 = new testclass();
            // Is seperate memory created for all the three objects that are created above ? 
            objtestclass1.setnumber(1);
            objtestclass2.setnumber(2);
            Console.Write(objtestclass1.number);
            Console.Write(objtestclass2.number);
            objtestclass3 = objtestclass1;
            //When we assign one object to another object is the existing memory of       the         objtestclass3 be cleared by GC
            Console.Write(objtestclass3.number);
            objtestclass3.setnumber(3);
            Console.Write(objtestclass3.number);
            Console.Write(objtestclass1.number);
            Console.Read();   
            }

            public class testclass
            {
                public int number = 0;
                public void setnumber(int a)
                {
                    number = a;
                }

            }
Run Code Online (Sandbox Code Playgroud)

谢谢.

Jon*_*eet 6

testclass堆的实例是在堆上.每个实例将包括:

  • 同步块
  • 类型参考
  • number

在32位Windows .NET上,这将占用12个字节.

方法(etc)中的局部变量将在堆栈中 - 但它们是引用,而不是对象.每个引用将是4个字节(再次在32位CLR上).Mainobjtestclass1

引用和对象之间的区别很重要.例如,在此行之后:

objtestclass3 = objtestclass1;
Run Code Online (Sandbox Code Playgroud)

您正在使两个变量的值相同 - 但这些值都是引用.换句话说,两个变量都指向同一个对象,因此如果您通过一个变量进行更改,您将能够通过另一个变量看到它.您可以将引用视为有点像URL - 如果我们都有相同的URL,并且我们其中一个人编辑它引用的页面,我们都会看到该编辑.

有关此内容的更多信息,请参阅有关引用类型的文章和有关内存的一篇文章.