Generics and calling overloaded method from difference class - precedence issue [duplicate]

帅比萌擦擦* 提交于 2019-12-05 02:07:55

The compiler has to decide at compile time which method to choose. It doesn't emit any code to decide at runtime which of the two overloads to pick. Because you haven't provided any evidence to the C# compiler that GetInt(T source) only works with byte structures, the compiler has to pick the other overload.

Or let me put it in a different perspective: if you remove the ToInt32(object) overload, your program fails to compile.

Rohit Vats

Compiler decides at compile time which method to execute.

I see through Reflector for IL code and found this -

.method public hidebysig static int32 GetInt(!T source) cil managed
{
    .maxstack 1
    .locals init (
        [0] int32 CS$1$0000)
    L_0000: nop 
    L_0001: ldarg.0 
    L_0002: box !T
    L_0007: call int32 ConsoleApplication1.Convert::ToInt32(object) <-- HERE
    L_000c: stloc.0 
    L_000d: br.s L_000f
    L_000f: ldloc.0 
    L_0010: ret 
}

As mentioned by Jon Skeet here, you can make a call to byte method using dynamic which provides typed information at execution time instead of compile time.

public static class Test<T>
{
    public static int GetInt(T source)
    {
        dynamic dynamicSource = source;
        return Convert.ToInt32(dynamicSource );
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!