在C#中双重调度? [英] Double dispatch in C#?

查看:121
本文介绍了在C#中双重调度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听过/阅读了这个词,但不太明白这是什么意思。

I have heard/read the term but don't quite understand what it means.

什么时候应该使用这种技术,我该怎么用?任何人都可以提供良好的代码示例?

When should I use this technique and how would I use it? Can anyone provide a good code sample?

推荐答案

访问者模式是以面向对象方式进行双重调度的一种方式

The visitor pattern is a way of doing double-dispatch in an object-oriented way.

当您希望根据运行时的类型(而不是编译时间)为给定的参数选择使用哪种方法。

It's useful for when you want to choose which method to use for a given argument based on its type at runtime rather than compile time.

双重发送是一种特殊情况,多次发送

Double dispatch is a special case of multiple dispatch.

当您在对象上调用虚拟方法时,这被认为是单调度,因为调用哪个实际方法取决于单个对象的类型。

When you call a virtual method on an object, that's considered single-dispatch because which actual method is called depends on the type of the single object.

对于双重分派,将考虑对象的类型和方法唯一参数的类型。这就像方法重载分辨率,除了参数类型在运行时以双调度而不是在编译时静态确定。

For double dispatch, both the object's type and the method sole argument's type is taken into account. This is like method overload resolution, except that the argument type is determined at runtime in double-dispatch instead of statically at compile-time.

在多分派中,一种方法可以有多个参数传递给它,使用哪个实现取决于每个参数的类型。类型评估的顺序取决于语言。在LISP中,它检查每种类型从头到尾。

In multiple-dispatch, a method can have multiple arguments passed to it and which implementation is used depends on each argument's type. The order that the types are evaluated depends on the language. In LISP, it checks each type from first to last.

具有多个调度的语言使用通用函数,这些函数只是函数脱机,不像通用方法,使用类型参数。

Languages with multiple dispatch make use of generic functions, which are just function delcarations and aren't like generic methods, which use type parameters.

要在C#中执行双重调度,您可以声明一个具有唯一对象参数的方法,然后使用具体方法具体类型:

To do double-dispatch in C#, you can declare a method with a sole object argument and then specific methods with specific types:

using System.Linq;  

class DoubleDispatch
{ 
    public T Foo<T>(object arg)
    { 
        var method = from m in GetType().GetMethods()
                   where    m.Name == "Foo" 
                         && m.GetParameters().Length==1
                         && arg.GetType().IsAssignableFrom
                                           (m.GetParameters()[0].GetType())
                         && m.ReturnType == typeof(T)
                   select m;

        return (T) method.Single().Invoke(this,new object[]{arg});          
    }

    public int Foo(int arg) { /* ... */ }

    static void Test() 
    { 
        object x = 5;
        Foo<int>(x); //should call Foo(int) via Foo<T>(object).
    }
}       

这篇关于在C#中双重调度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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