How to build double dispatch using extensions

半城伤御伤魂 提交于 2019-12-13 14:41:17

问题


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.



来源:https://stackoverflow.com/questions/25912603/how-to-build-double-dispatch-using-extensions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!