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


当前回答

int可以保存的字节数取决于你编译它的目的,所以当你为32位处理器编译程序时,它可以保存从2^32/2到-2^32/2+1的数字,而为64位编译时,它可以保存从2^64/2到-2^64/2+1的数字。Int32总是包含2^32个值。

编辑:忽略我的回答,我没有看到c#。我的答案是针对C和c++的。我从来没用过c#

其他回答

int和Int32之间没有区别,但由于int是一个语言关键字,许多人在风格上更喜欢它(就像string vs string)。

虽然它们(大部分)是相同的(参见下面的一个[错误]差异),但您绝对应该注意并应该使用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
}

还要考虑Int16。如果你需要在应用程序的内存中存储一个Integer类型,并且你关心使用的内存量,那么你可以使用Int16类型,因为它使用的内存更少,并且比Int32类型的最小/最大范围更小(这就是int类型)。

没关系。int是语言关键字,Int32是实际的系统类型。

也可以在这里看到我对相关问题的回答。

我使用int是为了防止Microsoft将整数的默认实现更改为一些新版本(我们称其为Int32b)。

然后,Microsoft可以将int别名更改为Int32b,我不需要更改任何代码就可以利用他们新的(希望是改进的)整数实现。

这同样适用于任何类型关键字。