C#:从generics方法调用非generics方法

class CustomClass 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方法? 我只想为不同类型提供不同的方法。

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

我很乐意提示。

最好的问候,克里斯

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

您可以使用dynamic类型在C#4.0中实现此目的:

 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()"); } }