我有一个类库,其中包含一些基类和派生自它们的其他类。在这个类库中,我利用多态性来做我想做的事。现在在一个消费应用程序中,我想根据子类的运行时类型更改某些代码的行为。所以假设如下:
public class Base { }
public class Child1 : Base { }
public class Child2 : Base { }
现在在消费应用程序中我想做如下事情(注意以下所有类都在消费应用程序中,不能在类库中引用):
public interface IMyInterface1 { }
public interface IMyInterface2 { }
public static class Extensions
{
public static void DoSomething(this Base myObj, Object dependency)
{
}
public static void DoSomething(this Child1 myObj, Object dependency)
{
IMyInterface1 myInterface = dependency as IMyInterface1;
if (myInterface != null)
{
//Do some Child1 specific logic here
}
}
public static void DoSomething(this Child2 myObj, Object dependency)
{
IMyInterface2 myInterface = dependency as IMyInterface2;
if (myInterface != null)
{
//Do some Child2 specific logic here
}
}
}
更新:
这是行不通的。它总是调用基类的扩展方法。有没有其他方法可以让我这样做并避免显式检查运行时类型?原因是因为可以添加更多从 Base
派生的类,并且相应的扩展方法可以来自其他一些外部程序集。
提前致谢。
最佳答案
正如@SLaks 已经声明的那样,您不能将该方法作为扩展方法调用(即使使用 dynamic
类型)...但是您可以使用 dynamic
调用静态方法类型
所以,虽然这会失败
Base base1 = new Child1();
(base1 as dynamic).DoSomething();
这会起作用
Base base1 = new Child1();
Extensions.DoSomething(base1 as dynamic);
关于c# - 通过扩展方法实现多态性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20707317/