How to build double dispatch using extensions

2019-07-03 04:21发布

问题:

I have a library that have a hierarchy of class as follow:

class Base {}
class A : Base {}
class B : Base {}

Now I wanted to do different thing depending on type of my object whether it is an A or a B. So I decide to go for and implement double dispatching to avoid checking type.

class ClientOfLibrary {

    public DoStuff(Base anObject)
    {
       anObject.MakeMeDoStuff(this);
    }

    private void DoStuffForanA(A anA);
    private void DoStuffForaB(B aB);
}

Now the canonical way of implementing double dispatch is to make the method MakeMeDoStuff abstract in Base and overload it in concrete class. But remember that Base, A and B are in library so I can not go and add does method freely.

Adding method extension wont work because there is no way to add an abstract extensions.

Any suggestion?

回答1:

You can just use dynamic calls:

class ClientOfLibrary {

    public DoStuff(Base o)
    {
       DoStuffInternal((dynamic)o);
    }

    private void DoStuffInternal(A anA) { }
    private void DoStuffInternal(B aB) { }
    private void DoStuffInternal(Base o) { /* unsupported type */ }
}

C# natively supports multiple dispatch since introduction of dynamic, so implementing visitor pattern is unnecessary in most cases.