C#:从泛型方法调用非泛型方法

Chr*_*ris 13 c# generics

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
}
Run Code Online (Sandbox Code Playgroud)

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

而是打印以下错误消息:"'CustomClass.init(bool)'的最佳重载方法匹配'有一些无效的参数"

我很乐意提示.

最好的问候,克里斯

Tim*_*mwi 34

编译器不能使用init(bool),因为在编译时无法知道Tbool.您要求的是动态调度 - 实际调用哪个方法取决于参数的运行时类型,并且无法在编译时确定.

您可以使用以下dynamic类型在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()");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • +1,这似乎是OP试图获得的.另外,有趣的是使用`dynamic`.我偶尔会想要使用带有类型的`switch`语句,这似乎是一种模拟效果的有趣方式. (2认同)