在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, string等),在访问静态方法时使用真实名称:

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

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

曾经,int数据类型与编译器目标机器的寄存器大小挂钩。例如,16位系统的编译器将使用16位整数。

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

使用Int或Int32都是一样的Int只是为了简化读者的代码。

使用可空变量Int?还是Int32 ?当您在数据库中处理包含null的字段时。这将使您避免大量的运行时问题。

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

int是一个c#关键字,是明确的。

大多数情况下,这并不重要,但有两件事与Int32相悖:

您需要有一个“using System;”语句。使用"int"不需要Using语句。 可以定义自己的名为Int32的类(这将是愚蠢和令人困惑的)。Int总是Int的意思。