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


当前回答

一些编译器在不同的平台上对int有不同的大小(不是c#特定的)

一些编码标准(MISRA C)要求所有使用的类型都指定大小(即Int32而不是int)。

为不同类型的变量指定前缀也很好(例如,b表示8位字节,w表示16位字,l表示32位长字=> Int32 lMyVariable)

您应该关心,因为它使您的代码更具可移植性和可维护性。

如果你总是要使用c#,而且c#规范在这方面永远不会改变,那么可移植可能不适用于c#。

可维护的ihmo将始终适用,因为维护代码的人可能不知道这个特定的c#规范,并且错过了int偶尔超过2147483647的错误。

在简单的for循环中,例如计算一年中的月份,您不会关心,但是当您在一个可能会owerflow的上下文中使用该变量时,您应该关心。

您还应该注意是否要对它进行逐位操作。

其他回答

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

我建议使用微软的StyleCop。

它类似于FxCop,但用于与样式相关的问题。默认配置与微软的内部样式指南相匹配,但也可以根据您的项目进行定制。

它可能需要一些时间来适应,但它肯定会使您的代码更好。

您可以将它包含在构建过程中,以自动检查是否违反。

你不应该关心大多数编程语言,除非你需要编写非常特定的数学函数,或者针对特定架构优化的代码……只要确保类型的大小足够你(例如,如果你知道你需要超过32位,就使用比Int更大的类型)

你不应该在意。如果大小是一个问题,我会使用字节,短,int,然后长。使用int型比int32大的唯一原因是需要一个大于2147483647或小于-2147483648的数。

除此之外,我不在乎,还有很多其他的事情需要关心。

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