在c#中,int和Int32是同一个东西,但我读过很多次int比Int32更受欢迎,没有给出原因。这是有原因的吗,我应该在意吗?
当前回答
虽然它们(大部分)是相同的(参见下面的一个[错误]差异),但您绝对应该注意并应该使用Int32。
The name for a 16-bit integer is Int16. For a 64 bit integer it's Int64, and for a 32-bit integer the intuitive choice is: int or Int32? The question of the size of a variable of type Int16, Int32, or Int64 is self-referencing, but the question of the size of a variable of type int is a perfectly valid question and questions, no matter how trivial, are distracting, lead to confusion, waste time, hinder discussion, etc. (the fact this question exists proves the point). Using Int32 promotes that the developer is conscious of their choice of type. How big is an int again? Oh yeah, 32. The likelihood that the size of the type will actually be considered is greater when the size is included in the name. Using Int32 also promotes knowledge of the other choices. When people aren't forced to at least recognize there are alternatives it become far too easy for int to become "THE integer type". The class within the framework intended to interact with 32-bit integers is named Int32. Once again, which is: more intuitive, less confusing, lacks an (unnecessary) translation (not a translation in the system, but in the mind of the developer), etc. int lMax = Int32.MaxValue or Int32 lMax = Int32.MaxValue? int isn't a keyword in all .NET languages. Although there are arguments why it's not likely to ever change, int may not always be an Int32.
缺点是要多输入两个字符和[bug]。
这不会编译
public enum MyEnum : Int32
{
AEnum = 0
}
但这将:
public enum MyEnum : int
{
AEnum = 0
}
其他回答
这两者确实是同义的;int看起来会更熟悉一些,Int32让那些阅读你的代码的人更清楚地看到32位。我倾向于在我只需要“一个整数”的地方使用int,在大小很重要的地方使用Int32(密码代码,结构),这样未来的维护者就会知道在适当的情况下扩大int是安全的,但应该注意以同样的方式改变Int32。
结果代码将是相同的:区别纯粹是可读性或代码外观。
这在实践中没有什么区别,最终你会采用你自己的惯例。我倾向于在分配类型时使用关键字,在使用静态方法时使用类版本等:
int total = Int32.Parse("1009");
根据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
你不应该在乎。大多数时候你应该使用int。它将有助于将来将程序移植到更广泛的体系结构(目前int是System的别名。Int32,但这可能会改变)。只有当变量的位宽很重要时(例如:要控制结构体在内存中的布局),才应该使用int32和其他变量(与"using System;"相关联)。
使用Int32类型需要对System或完全限定(System.Int32)的命名空间引用。我倾向于int,因为它不需要名称空间导入,因此在某些情况下减少了名称空间冲突的机会。当编译为IL时,两者之间没有区别。