差異

2012-11-01 100 views
2

可能重複:
Where and why use int a=new int?差異

什麼是下面這兩者之間的區別?

int i =0; 
int i = new int(); 

內存分配情況是否有區別? 還有其他區別嗎?

+0

變量「i」的隱式和顯式聲明。 – Mullaly

+0

@穆拉利 - 怎麼這樣? (FWIW:'0 == new int()== default(int)') – 2012-11-01 05:38:26

+1

第一個顯然是毫不含糊的,即使對不經意的讀者也是如此。 – tvanfosson

回答

0

第一個

int i = 0; 

初始化名i的一個新的整數。然後,將其值設置爲0

而第二個

int i = new int(); 

初始化名稱i的爲默認值的新的整數(這是0)。這也類似於

int i = default(int); 

謝謝,
我希望對您有所幫助:)

+2

在所有情況下,該值都設置爲0.它不僅爲變量分配空間並創建符號表條目。 – tvanfosson

+0

@tvanfosson我同意你的意見。沒有區別,但我只是想說明每件事情。如果值改變,它將不會相同:) –

+0

int i = new int();這也設置爲0. –

5

的他們都編譯爲同樣的事情。

假設您有:

static void Main(string[] args) 
{ 
    int i = 0; 
    int j = new int(); 

    Console.Write("{0}{1}", i, j); 
} 

如果您在Release模式構建和看到ILSpy的可執行文件,它編譯爲:

private static void Main(string[] args) 
{ 
     int i = 0; 
     int j = 0; 
     Console.Write("{0}{1}", i, j); 
} 

new int()是相同default(int)

這裏IL

.method private hidebysig static void Main(string[] args) cil managed 
{ 
    .entrypoint 
    // Code size  27 (0x1b) 
    .maxstack 3 
    .locals init ([0] int32 i, 
      [1] int32 j) 
    IL_0000: ldc.i4.0 
    IL_0001: stloc.0 
    IL_0002: ldc.i4.0 
    IL_0003: stloc.1 
    IL_0004: ldstr  "{0}{1}" 
    IL_0009: ldloc.0 
    IL_000a: box  [mscorlib]System.Int32 
    IL_000f: ldloc.1 
    IL_0010: box  [mscorlib]System.Int32 
    IL_0015: call  void [mscorlib]System.Console::Write(string, 
                  object, 
                  object) 
    IL_001a: ret 
} // end of method Program::Main