2015-08-15 28 views
-1

這兩種擴展方法有什麼區別?相似的擴展方法 - 有什麼區別嗎?

public static class Test 
{ 
    public static int First<T>(this T obj) 
    { 
     return 2; 
    } 

    public static int Second(this object obj) 
    { 
     return 2; 
    } 
} 
+3

是:)另一個問題? – Backs

+1

雖然這個問題可以用更詳細的信息來表達,但是我真的不認爲它是那麼糟糕 - 並且可能是一個真正的好問題,並且有更多的細節。 –

回答

14

有一些差異,是的。第一個不會填充值的類型 - 但會結束JIT,爲不同的類型參數多次編譯該方法(一次爲所有引用類型,一次爲每個值類型)。

所以:

byte x1 = 10; 
int y1 = x1.First(); // No boxing 

byte x2 = 10; 
int y2 = x2.Second(); // Boxes before the call 

的IL產生的是:

IL_0001: ldc.i4.s 10 
IL_0003: stloc.0 
IL_0004: ldloc.0 
IL_0005: call  int32 Test::First<uint8>(!!0) 
IL_000a: stloc.1 
IL_000b: ldc.i4.s 10 
IL_000d: stloc.2 
IL_000e: ldloc.2 
IL_000f: box  [mscorlib]System.Byte 
IL_0014: call  int32 Test::Second(object) 

此外,您First擴展方法中,你可以分別從執行得到編譯時T時間obj引用的對象的類型。因此,例如,改變的方法正文:

public static class Test 
{ 
    public static int First<T>(this T obj) 
    { 
     Console.WriteLine("Compile-time type: {0}", typeof(T)); 
     Console.WriteLine("Execution-time type: {0}", obj.GetType()); 
     return 2; 
    } 

    public static int Second(this object obj) 
    { 
     // No compile-time type to know about 
     Console.WriteLine("Execution-time type: {0}", obj.GetType()); 
     return 2; 
    } 
} 

然後:

Stream foo = new MemoryStream(); 
foo.First(); // Will print Stream, then MemoryStream 
foo.Second(); // Only knows about MemoryStream 
+0

除此之外,官方文檔對於很好的示例非常有用:[Boxing and Unboxing(C#編程指南)](https://msdn.microsoft.com/en-us/library/yz2be5wk.aspx) – Gustav

+0

謝謝是非常有幫助的 – UnderNotic

相關問題