gpt4 book ai didi

c# - .Net/C# : what's the real size of an integer?

转载 作者:行者123 更新时间:2023-11-30 13:09:01 24 4
gpt4 key购买 nike

在 .Net 中,整数是值类型,这意味着它存储在堆栈中。整数也是类(通常是 System.Int32)。它们有 CompareTo、Equals 等方法,...因此,它们应该在堆栈上占用四个以上的字节。然而,下面的示例显示它们恰好占用 4 个字节:

unsafe static void Main()
{
int a = 2, b = 4;
Console.WriteLine("Adress of a : {0}", (int)&a);
Console.WriteLine("Adress of b : {0}", (int)&b);
Console.WriteLine("Size of integer: {0}", (int)(&a) - (int)(&b));
}

输出:

Adress of a : 1372876
Adress of b : 1372872
Size of integer: 4

CLR 是否对整数和其他值类型(float、long、double...)进行了特殊处理?

最佳答案

不,它们是值类型这一事实并不意味着它们存储在堆栈中。这意味着它们已存储 wherever the variable lives .

但是,嘿,让我们开始处理局部变量业务,此时(没有捕获等)它们确实存在于堆栈中。它们占用 4 个字节。他们为什么要拿更多?堆栈上不需要 vtable,因为元数据已经指定了类型:关于将调用哪些虚拟方法等没有歧义。

编辑:正如 Shawn 在评论中指出的(但我想让它更明显),System.Int32是结构体,不是类。 (事实上​​ CLR 会创建影子引用类型来覆盖装箱的 int 值,但那是另一回事。)

关于c# - .Net/C# : what's the real size of an integer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/600607/

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