类似的扩展方法 - 有什么区别吗?

Und*_*tic -1 c# generics extension-methods

这两种扩展方法有什么区别?

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

    public static int Second(this object obj)
    {
        return 2;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 14

有一些不同,是的.第一个不会包装值类型 - 但最终会为不同的类型参数多次编译方法(一次针对所有引用类型,一次针对每个值类型).

所以:

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

byte x2 = 10;
int y2 = x2.Second(); // Boxes before the call
Run Code Online (Sandbox Code Playgroud)

产生的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)
Run Code Online (Sandbox Code Playgroud)

此外,在First扩展方法中,您可以获得与引用的对象的执行时类型分开的编译时类型.例如,更改方法的主体:Tobj

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

Stream foo = new MemoryStream();
foo.First(); // Will print Stream, then MemoryStream
foo.Second(); // Only knows about MemoryStream
Run Code Online (Sandbox Code Playgroud)