Should I use int or Int32

2018-12-31 15:43发布

In C#, int and Int32 are the same thing, but I've read a number of times that int is preferred over Int32 with no reason given. Is there a reason, and should I care?

30条回答
墨雨无痕
2楼-- · 2018-12-31 16:25

They both declare 32 bit integers, and as other posters stated, which one you use is mostly a matter of syntactic style. However they don't always behave the same way. For instance, the C# compiler won't allow this:

public enum MyEnum : Int32
{
    member1 = 0
}

but it will allow this:

public enum MyEnum : int
{
    member1 = 0
}

Go figure.

查看更多
浅入江南
3楼-- · 2018-12-31 16:25

There is no difference between int and Int32, but as int is a language keyword many people prefer it stylistically (just as with string vs String).

查看更多
骚的不知所云
4楼-- · 2018-12-31 16:25

Once upon a time, the int datatype was pegged to the register size of the machine targeted by the compiler. So, for example, a compiler for a 16-bit system would use a 16-bit integer.

However, we thankfully don't see much 16-bit any more, and when 64-bit started to get popular people were more concerned with making it compatible with older software and 32-bit had been around so long that for most compilers an int is just assumed to be 32 bits.

查看更多
步步皆殇っ
5楼-- · 2018-12-31 16:25

int is an alias for System.Int32, as defined in this table: Built-In Types Table (C# Reference)

查看更多
浪荡孟婆
6楼-- · 2018-12-31 16:26

I always use the aliased types (int, string, etc.) when defining a variable and use the real name when accessing a static method:

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

It just seems ugly to see something like int.TryParse(). There's no other reason I do this other than style.

查看更多
萌妹纸的霸气范
7楼-- · 2018-12-31 16:26

It makes no difference in practice and in time you will adopt your own convention. I tend to use the keyword when assigning a type, and the class version when using static methods and such:

int total = Int32.Parse("1009");

查看更多
登录 后发表回答