在c#中,int和Int32是同一个东西,但我读过很多次int比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数据类型与编译器目标机器的寄存器大小挂钩。例如,16位系统的编译器将使用16位整数。

然而,谢天谢地,我们已经很少看到16位了,当64位开始流行时,人们更关心的是使它与旧软件兼容,32位已经存在了很长时间,对于大多数编译器来说,int只是假设为32位。

我总是在定义变量时使用别名类型(int, string等),在访问静态方法时使用真实名称:

int x, y;
...
String.Format ("{0}x{1}", x, y);

看到像int.TryParse()这样的东西似乎很难看。除了风格,我这么做没有别的原因。

如前所述,int = Int32。为了安全起见,请确保始终使用int. minvalue /int。MaxValue在实现任何关心数据类型边界的东西时。假设. net决定int现在是Int64,那么你的代码就不那么依赖于边界了。

使用Int32类型需要对System或完全限定(System.Int32)的命名空间引用。我倾向于int,因为它不需要名称空间导入,因此在某些情况下减少了名称空间冲突的机会。当编译为IL时,两者之间没有区别。

根据Visual Studio 2012中的即时窗口,Int32是int型,Int64是long型。输出如下:

sizeof(int)
4
sizeof(Int32)
4
sizeof(Int64)
8
Int32
int
    base {System.ValueType}: System.ValueType
    MaxValue: 2147483647
    MinValue: -2147483648
Int64
long
    base {System.ValueType}: System.ValueType
    MaxValue: 9223372036854775807
    MinValue: -9223372036854775808
int
int
    base {System.ValueType}: System.ValueType
    MaxValue: 2147483647
    MinValue: -2147483648