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

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

问题描述

我听过/阅读期限,但不明白这意味着什么。

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

当我使用这个技术,我会如何使用呢?任何人都可以提供良好的code样?

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

推荐答案

示例:的访问者模式是在面向对象的方式做双重分发的方式

Example: 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.

定义:双调度为多分派的一个特殊情况即可。

当你调用一个虚方法的对象上,这被认为单分派,因为它实际的方法被调用依赖于单个对象的类型。

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.

与多个调度化妆使用的通用功能,它们只是功能delcarations而不像一般的方法,它使用类型参数的语言。

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天全站免登陆