This question already has answers here:
Should I use int or Int32
                                
                                    (31个答案)
                                
                        
                                5年前关闭。
            
                    
int和Int32的优点/缺点是什么?为什么我们要使用第一而不是第二?

最佳答案

它们实际上是相同的-都声明32位整数,并且大多数情况下它们的行为是相同的。速记int只是Int32系统类型的别名。

根据语言规范:


  4.1.4简单类型C#提供了一组称为简单类型的预定义结构类型。简单类型通过保留字来标识,但是这些保留字只是System名称空间中预定义结构类型的别名,如下表所述。


这是简单类型及其别名的列表:

Reserved word   Aliased type
sbyte           System.SByte
byte            System.Byte
short           System.Int16
ushort          System.UInt16
int             System.Int32
uint            System.UInt32
long            System.Int64
ulong           System.UInt64
char            System.Char
float           System.Single
double          System.Double
bool            System.Boolean
decimal         System.Decimal

There are only a couple instances I can think of where using one over the other would matter. The first is where it's important to know the limitations of the type (e.g. cryptography), but that's only for readability. The other is with an enum:

public enum MyEnum : Int32
{
    member1 = 0 //no good
}

public enum MyEnum : int
{
    member1 = 0 //all is well
}

关于c# - int和Int32的优缺点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10484799/

10-13 06:53