gpt4 book ai didi

c# - C#中将值类型装箱到引用类型需要多少内存?

转载 作者:行者123 更新时间:2023-11-30 19:40:08 25 4
gpt4 key购买 nike

public class A
{
public static void Main(string[] args)
{
int num = 13; // It stores in Stack and takes 4 bytes
object obj = 13; // Where it is Stored (Stack or Heap)?
//How much size obj require?
}
}

我只想知道 obj 需要的额外位以及为什么?

最佳答案

首先帮助解释“为什么”,来自 C# 5 规范:第 4.3.1 节装箱转换

The actual process of boxing a value of a non-nullable-value-type is best explained by imagining the existence of a generic boxing class, which behaves as if it were declared as follows:

sealed class Box<T>: System.ValueType
{
T value;
public Box(T t) {
value = t;
}
}

Boxing of a value v of type T now consists of executing the expression new Box(v), and returning the resulting instance as a value of type object. Thus, the statements

int i = 123;
object box = i;

conceptually correspond to

int i = 123;
object box = new Box<int>(i);

要回答是存储在栈上还是堆上,答案都是。参见 Boxing and Unboxing在 MSDN 上。

Consider the following declaration of a value-type variable:

int i = 123;

The following statement implicitly applies the boxing operation on the variable i:

// Boxing copies the value of i into object o. 
object o = i;

The result of this statement is creating an object reference o, on the stack, that references a value of the type int, on the heap. This value is a copy of the value-type value assigned to the variable i. The difference between the two variables, i and o, is illustrated in the following figure. enter image description here

所以栈上存储了sizeof(Object)字节,堆上存储了sizeof(int) + Class开销。

我找不到任何关于开销有多大的好文档,它的大小很可能是 8 到 16 个字节。

关于c# - C#中将值类型装箱到引用类型需要多少内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24710852/

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