简体   繁体   中英

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; }
}

Given the code block above does not actually do anything but call the first DoSomethingElse method, what would be a clever approach to having the correct method call based on the real type of the parameters passed to the DoSomething method?

Is there a way I can get the method call resolved at runtime, or do I have to go with an "if typeof" style of code resolution?

You can use the dynamic keyword:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM