簡體   English   中英

C#:從泛型方法調用非泛型方法

[英]C#: Call non-generic method from generic method

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
}

你好。 這似乎是一個簡單的問題,但是我在Internet上找不到答案:為什么編譯器不使用init方法? 我只是想為不同的類型提供不同的方法。

而是打印以下錯誤消息:“'CustomClass.init(bool)'的最佳重載方法匹配具有一些無效的參數”

我很高興有一個提示。

最好的問候,克里斯

編譯器不能使用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()");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM