簡體   English   中英

C#增強方法重載決議

[英]C# enhanced Method overload resolution

class Base {}
class ClassA : Base {}
class ClassB : Base {}
public static class ExtensionFunctions
{
    public static bool DoSomething(this Base lhs, Base rhs)
    {
        return lhs.DoSomethingElse(rhs);
    }

    public static bool DoSomethingElse(this Base lhs, Base rhs) { return true; }
    public static bool DoSomethingElse(this ClassA lhs, ClassA rhs) { return false; }
    public static bool DoSomethingElse(this ClassA lhs, ClassB rhs) { return false; }
    public static bool DoSomethingElse(this ClassB lhs, ClassA rhs) { return false; }
    public static bool DoSomethingElse(this ClassB lhs, ClassB rhs) { return false; }
}

鑒於上面的代碼塊實際上並沒有做任何事情,只是調用第一個DoSomethingElse方法,根據傳遞給DoSomething方法的參數的實際類型,有一個聰明的方法來進行正確的方法調用?

有沒有辦法讓我在運行時解析方法調用,或者我是否必須使用“if typeof”樣式的代碼解析?

您可以使用dynamic關鍵字:

public static bool DoSomething(this Base lhs, Base rhs)  
{
    return DoSomethingElse((dynamic)lhs, (dynamic)rhs);  
}

暫無
暫無

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

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