C#: Call non-generic method from generic method

前端 未结 1 2171
一生所求
一生所求 2021-02-19 15:02
class CustomClass where T: bool
{
    public CustomClass(T defaultValue)
    {
        init(defaultValue); // why can\'t the compiler just use void init(bool) h         


        
1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-19 15:21

    The compiler cannot use init(bool) because at compile-time it cannot know that T is bool. What you are asking for is dynamic dispatch — which method is actually being called depends on the run-time type of the argument and cannot be determined at compile-time.

    You can achieve this in C# 4.0 by using the dynamic type:

    class CustomClass
    {
        public CustomClass(T defaultValue)
        {
            init((dynamic)defaultValue);
        }
        private void init(bool defaultValue) { Console.WriteLine("bool"); }
        private void init(int defaultValue) { Console.WriteLine("int"); }
        private void init(object defaultValue) {
            Console.WriteLine("fallback for all other types that don’t have "+
                              "a more specific init()");
        }
    }
    

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