如何使用扩展构建双重调度 [英] How to build double dispatch using extensions

查看:93
本文介绍了如何使用扩展构建双重调度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图书馆,图书馆的课程层次结构如下:

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

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

现在我想根据对象的类型(是A还是B)做不同的事情. 因此,我决定去执行双重调度,以避免检查类型.

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);
}

现在,实现双重调度的规范方法是在Base中使方法MakeMeDoStuff抽象,并在具体类中重载它.但是请记住,BaseAB都在库中,所以我不能随意添加方法.

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.

有什么建议吗?

推荐答案

您可以只使用dynamic调用:

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 */ }
}

自引入dynamic以来,C#本机支持多种调度,因此在大多数情况下无需实现访客模式.

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

这篇关于如何使用扩展构建双重调度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆