C# - 在类中使用多态,我没写

zil*_*n01 2 c# architecture polymorphism inheritance

在我无法修改的类中实现多态行为的最佳方法是什么?我目前有一些代码,如:

if(obj is ClassA) {
    // ...
} else if(obj is ClassB) {
    // ...
} else if ...
Run Code Online (Sandbox Code Playgroud)

显而易见的答案是向基类添加一个虚方法,但遗憾的是代码在不同的程序集中,我无法修改它.有没有比上面的丑陋和慢速代码更好的方法来处理这个问题?

har*_*rpo 9

嗯...似乎更适合适配器.

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

看起来像很多代码,但它会使客户端代码更接近你想要的.此外,它还可以让您有机会思考您实际使用的界面.


Ros*_*ant 5

查看访客模式.这使您可以在不更改类的情况下将虚拟方法添加到类中.如果您正在使用的基类没有Visit方法,则需要使用带有动态强制转换的扩展方法.这是一些示例代码:

public class Main
{
    public static void Example()
    {
        Base a = new GirlChild();
        var v = new Visitor();
        a.Visit(v);
    }
}

static class Ext
{
    public static void Visit(this object b, Visitor v)
    {
        ((dynamic)v).Visit((dynamic)b);
    }
}

public class Visitor
{
    public void Visit(Base b)
    {
        throw new NotImplementedException();
    }

    public void Visit(BoyChild b)
    {
        Console.WriteLine("It's a boy!");
    }

    public void Visit(GirlChild g)
    {
        Console.WriteLine("It's a girl!");            
    }
}
//Below this line are the classes you don't have to change.
public class Base
{
}

public class BoyChild : Base
{
}

public class GirlChild : Base
{
}
Run Code Online (Sandbox Code Playgroud)