简体   繁体   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; }
}

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? 鉴于上面的代码块实际上并没有做任何事情,只是调用第一个DoSomethingElse方法,根据传递给DoSomething方法的参数的实际类型,有一个聪明的方法来进行正确的方法调用?

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? 有没有办法让我在运行时解析方法调用,或者我是否必须使用“if typeof”样式的代码解析?

You can use the dynamic keyword: 您可以使用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