在c#中,int和Int32是同一个东西,但我读过很多次int比Int32更受欢迎,没有给出原因。这是有原因的吗,我应该在意吗?


当前回答

int是System的别名。Int32,定义如下: 内置类型表(c#参考)

其他回答

ECMA-334:2006 c#语言规范(p18)

每个预定义类型都是系统提供类型的简写。例如,关键字int指向结构体System.Int32。就风格而言,使用关键字优于使用完整的系统类型名。

我总是使用系统类型——例如,Int32而不是int。我在阅读了Applied . net Framework Programming之后采用了这种做法——作者Jeffrey Richter为使用完整类型名做了一个很好的例子。以下两点让我印象深刻:

Type names can vary between .NET languages. For example, in C#, long maps to System.Int64 while in C++ with managed extensions, long maps to Int32. Since languages can be mixed-and-matched while using .NET, you can be sure that using the explicit class name will always be clearer, no matter the reader's preferred language. Many framework methods have type names as part of their method names: BinaryReader br = new BinaryReader( /* ... */ ); float val = br.ReadSingle(); // OK, but it looks a little odd... Single val = br.ReadSingle(); // OK, and is easier to read

我知道最好的做法是使用int,所有MSDN代码都使用int。然而,据我所知,除了标准化和一致性之外,没有其他原因。

int是c#语言中System的快捷方式。Int32

虽然这确实意味着微软可能会改变这种映射,但FogCreek讨论的一篇文章指出[来源]

“关于64位的问题——微软确实在开发64位版本的。net框架,但我很确定int不会在该系统上映射到64位。

原因:

1. c# ECMA标准明确规定int是32位,long是64位。

2. 微软在框架1.1版本中引入了额外的属性和方法,返回长值而不是int值,例如Array。除了Array.GetLength之外的GetLongLength。

所以我认为可以肯定地说,所有内置的c#类型都将保持当前的映射。”

int与System相同。Int32,当编译时,它将在CIL中变成相同的东西。

我们在c#中按照惯例使用int,因为c#希望看起来像C和c++(以及Java),这就是我们在那里使用的……

顺便说一句,我最终使用的是系统。Int32时声明各种Windows API函数的导入。我不确定这是否是一个定义的约定,但它提醒我,我要去一个外部DLL…