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

查看:36
本文介绍了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.

双分派是多分派的特例.

当您在对象上调用虚拟方法时,这被视为单分派,因为调用的实际方法取决于单个对象的类型.

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.

在multiple-dispatch 中,一个方法可以有多个参数传递给它,使用哪种实现取决于每个参数的类型.评估类型的顺序取决于语言.在 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天全站免登陆