在我无法修改的类中实现多态行为的最佳方法是什么?我目前有一些代码,例如:
if(obj is ClassA) {
// ...
} else if(obj is ClassB) {
// ...
} else if ...
显而易见的答案是向基类添加一个虚方法,但不幸的是代码在不同的程序集中,我无法修改它。有没有比上面丑陋而缓慢的代码更好的方法来处理这个问题?
最佳答案
嗯……似乎更适合 Adapter .
public interface ITheInterfaceYouNeed
{
void DoWhatYouWant();
}
public class MyA : ITheInterfaceYouNeed
{
protected ClassA _actualA;
public MyA( ClassA actualA )
{
_actualA = actualA;
}
public void DoWhatYouWant()
{
_actualA.DoWhatADoes();
}
}
public class MyB : ITheInterfaceYouNeed
{
protected ClassB _actualB;
public MyB( ClassB actualB )
{
_actualB = actualB;
}
public void DoWhatYouWant()
{
_actualB.DoWhatBDoes();
}
}
看起来代码很多,但它会让客户端代码更接近你想要的。此外,它会让您有机会思考您实际使用的界面是什么。
关于C# - 在我没有编写的类中使用多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/683401/