Does new 'dynamic' variable type in .NET 4.0 solve the single/multiple method dispatch issue in CLR?

百般思念 提交于 2019-12-04 09:49:58

问题


The problem of single dispatch is mostly familiar to people engaged in coding with statically typed languages like Java and C#. The basic idea is:

While the runtime polymorphism allows us to dispatch to the right method call according to the type (runtime type) of receiver, for example:

IAnimal mything = new Cat();
mything.chop();

The method call will be performed according to the runtime type of mything, namely Cat. This is the single dispatch capability (which is present in Java/C#).

Now, if you need to dispatch not only on the runtime type of receiver, but on the types of (multiple) arguments either, you face a little problem:

public class MyAcceptor {  
    public void accept (IVisitor vst) {...}   
    public void accept (EnhancedConcreteVisitor vst) {...}  
}

The second method never gets called, because in our 'consumer' code we just tend to treat different types of objects (visitors in my example) by their common supertype or interface.

That's why I ask - because dynamic typing allows the multiple dispatch polymorphism and C# 4.0 has that dynamic keyword ;)


回答1:


Yes, dynamic typing allows multiple dispatch - and no, you don't have to create your own dynamic object to do it.

Suppose we wanted to implement Enumerable.Count() ourselves, and we didn't want a load of "if (source is IList)" tests in our code. We could write it like this:

public static class Enumerable
{
    public static int Count<T>(this IEnumerable<T> source)
    {
        dynamic d = source;
        return CountImpl(d);
    }

    private static int CountImpl<T>(ICollection<T> collection)
    {
        return collection.Count;
    }

    private static int CountImpl(ICollection collection)
    {
        return collection.Count;
    }

    private static int CountImpl<T>(string text)
    {
        return text.Length;
    }

    private static int CountImpl<T>(IEnumerable<T> source)
    {
        // Fallback
        int count = 0;
        foreach (T t in source)
        {
            count++;
        }
        return count;
    }
}

I'm not saying it would be a good idea, but that's how it would work :)

Note that you need to be careful not to introduce situations where you could end up with an ambiguous call for some types. This wouldn't be an issue using classes for parameters, but consider that a single class can implement multiple interfaces.




回答2:


Yes, you can create DLR types that do arbitrarily complex dispatch. Check out http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx



来源:https://stackoverflow.com/questions/2752523/does-new-dynamic-variable-type-in-net-4-0-solve-the-single-multiple-method-di

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