如何内存分配给引用类型在C#? [英] How memory is allocated to reference types in C#?

查看:111
本文介绍了如何内存分配给引用类型在C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我在引用的内存分配有些疑惑types.Please澄清我的问题,这是在评论下方之间的code。

Hi I have some doubts in the memory allocation of the reference types.Please clarify my questions that are commented in between the code below.

 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;
                }

            }

感谢。

推荐答案

的TestClass 的实例是在堆上。每个实例将包括:

The instance of testclass is on the heap. Each instance will consist of:

  • 在同步块
  • A型参考
  • 字段

在32位的Windows .NET,这将需要12个字节。

On a 32-bit Windows .NET, this will take 12 bytes.

本地的的方法中的变量( objtestclass1 等)将在堆栈 - 但他们的引用的,而不是对象。每个参考值将是4个字节(再次在32位,CLR)。

The local variables within the Main method (objtestclass1 etc) will be on the stack - but they're references, not objects. Each reference will be 4 bytes (again on a 32-bit CLR).

的引用和对象之间的区别是很重要的。例如,该行之后:

The difference between references and objects is important. For example, after this line:

objtestclass3 = objtestclass1;

您正在做的两个值的变量的是相同的 - 但这些值都为引用。换句话说,这两个变量的参考的同一个对象,因此如果通过一个变量的变化,你就可以通过另一个变量才能看到它。你可以把引用作为有点像URL的 - 如果我们都有相同的URL,而我们中的一个编辑它指的是页面,我们俩看到修改

You're making the values of the two variables the same - but those values are both references. In other words, both variables refer to the same object, so if you make a change via one variable you'll be able to see it via the other variable. You can think of the reference as a bit like a URL - if we both have the same URL, and one of us edits the page it refers to, we'll both see that edit.

有关这方面的详细信息,请参阅我的文章就引用类型和另一个上的memory

For more information on this, see my article on reference types and another one on memory.

这篇关于如何内存分配给引用类型在C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆