C#:致电泛型方法非泛型方法 [英] C#: Call non-generic method from generic method

查看:96
本文介绍了C#:致电泛型方法非泛型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class CustomClass<T> where T: bool
{
    public CustomClass(T defaultValue)
    {
        init(defaultValue); // why can't the compiler just use void init(bool) here?
    }
    public void init(bool defaultValue)
    {

    }
    // public void init(int defaultValue) will be implemented later
}

您好。这似乎是一个简单的问题,但我不能在互联网上找到一个答案:为什么不能编译器使用的的init 的方法是什么?我只是想提供不同类型不同的方法

Hello. This seems to be a simple question, but I couldn't find an answer on the Internet: Why won't the compiler use the init method? I simply want to provide different methods for different types.

相反,它打印出以下错误信息:
为CustomClass.init的最佳重载的方法匹配(布尔)'有一些无效参数

Instead it prints the following error message: "The best overloaded method match for 'CustomClass.init(bool)' has some invalid arguments"

我会很高兴的暗示。

最好的问候,
克里斯

Best regards, Chris

推荐答案

编译器不能使用的init(布尔)因为在编译时无法知道 T 布尔。你所要求的是动态调度的 - 这方法实际上是被称为取决于参数的运行时类型,不能在编译时确定

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.

您可以使用动态实现这在C#4.0 键入:

class CustomClass<T>
{
    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()");
    }
}

这篇关于C#:致电泛型方法非泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆