C# 类似的扩展方法-有什么不同吗?

C# 类似的扩展方法-有什么不同吗?,c#,generics,extension-methods,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; } } 公共静态类测试 { 公共静态int优先(此T对象) { 返回2; } 公共静态整数秒(此对象obj

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

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

    public static int Second(this object obj)
    {
        return 2;
    }
}
公共静态类测试
{
公共静态int优先(此T对象)
{
返回2;
}
公共静态整数秒(此对象obj)
{
返回2;
}
}

有一些不同,是的。第一种方法不会限制值类型,但最终会针对不同的类型参数多次JIT编译方法(一次用于所有引用类型,一次用于每个值类型)

因此:

生成的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)
然后:


是:)另一个问题?虽然这个问题可以更详细地表达OP想要什么,但我真的不认为它有那么糟糕——而且可能是一个真正好的问题,再详细一点。除此之外,官方文档非常有用,有很好的例子:谢谢,这非常有用
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)
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