gpt4 book ai didi

c# - C# 中的引用类型如何分配内存?

转载 作者:太空宇宙 更新时间:2023-11-03 18:18:57 24 4
gpt4 key购买 nike

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

 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 的实例在堆上。每个实例将包括:

  • 一个同步块(synchronized block)
  • 类型引用
  • 字段number

  • 在 32 位 Windows .NET 上,这将占用 12 个字节。
    Main 中的局部变量方法( objtestclass1 等)将在堆栈中 - 但它们是引用,而不是对象。每个引用将是 4 个字节(同样在 32 位 CLR 上)。

    引用和对象之间的区别很重要。例如,在这一行之后:
    objtestclass3 = objtestclass1;

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

    有关这方面的更多信息,请参阅 my article on reference types另一个在 memory .

    关于c# - C# 中的引用类型如何分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1754903/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com