【发布时间】:2013-12-20 15:50:32
【问题描述】:
我有一个类库,其中包含一些基类和其他派生自它们的类。在这个类库中,我利用多态性来做我想做的事。现在在一个消费应用程序中,我想根据子类的运行时类型更改一些代码的行为。所以假设如下:
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 是对的。它总是调用基类的扩展方法。
标签: c# .net polymorphism extension-methods