Skip to content
标签
欢迎扫码关注公众号

C# int vs Int32

intInt32 有什么区别?

很多人都认为 int 是值类型,Int32 是引用类型。

还有些人认为 int 在 32 位系统上是 32 位整数,在 64 位系统上是 64 位整数。

这些说法对吗?让我们写段代码来验证一下。

csharp
static void Main(string[] args)
{
    int a = 0;
    System.Int32 b = 0;
    int c = new int();
    System.Int32 d = new System.Int32();
}

上面我们用定义了 4 个变量,并且用不同的方式做了初始化。

使用 ILDasm 命令反编译后的 IL 代码如下:

csharp
.method /*06000001*/ private hidebysig static 
        void  Main(string[] args) cil managed
// SIG: 00 01 01 1D 0E
{
.entrypoint
// 方法在 RVA 0x2050 处开始
// 代码大小       10 (0xa)
.maxstack  1
.locals /*11000001*/ init ([0] int32 a,
            [1] int32 b,
            [2] int32 c,
            [3] int32 d)
IL_0000:  /* 00   |                  */ nop
IL_0001:  /* 16   |                  */ ldc.i4.0
IL_0002:  /* 0A   |                  */ stloc.0
IL_0003:  /* 16   |                  */ ldc.i4.0
IL_0004:  /* 0B   |                  */ stloc.1
IL_0005:  /* 16   |                  */ ldc.i4.0
IL_0006:  /* 0C   |                  */ stloc.2
IL_0007:  /* 16   |                  */ ldc.i4.0
IL_0008:  /* 0D   |                  */ stloc.3
IL_0009:  /* 2A   |                  */ ret
} // end of method Program::Main

从上面的代码可以看出,4 个本地变量 abcd,类型都是 int32

赋值操作都是先使用 ldc 命令加载到栈,然后使用 stloc 命令弹出并赋值到上面定义的变量。

没有多余的 box(装箱)和 unbox(拆箱)操作。

这说明 intSystem.Int32 都是 32 位整数,都是值类型。

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.