C#: Generic method doesn't call specific method overload

前端 未结 1 1273
灰色年华
灰色年华 2021-01-17 22:35

I am trying to create a generic method in C#, which will call different methods based on the argument datatype in its body and process their result afterwards. I am trying t

相关标签:
1条回答
  • 2021-01-17 23:04

    Is there any way correct this behavior?

    It's already the correct behaviour according to the C# language specification. The overload of Func called within FuncWrap is normally determined at compile time, so it can't pick a different Func overload based on the execution-time type.

    One way of changing the behaviour, however, is to use dynamic typing:

    static void FuncWrap<T>(T val)
    {
        Console.Write("Wrap: ");
        dynamic x = val;
        Func(x);
    }
    

    That will now perform overload resolution at execution time based on the actual type of the value of x. This incurs a performance cost, but should do what you want it to.

    Alternatively, you could hard-code knowledge of the overloads:

    static void FuncWrap<T>(T val)
    {
        Console.Write("Wrap: ");
        if (typeof(T) == typeof(string))
        {
            Func((string)(object)val);
        }
        else if (typeof(T) == typeof(int))
        {
            Func((int)(object)val);
        }
        else
        {
            Func(val);
        }
    }
    

    That's clearly pretty horrible though.

    0 讨论(0)
提交回复
热议问题