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

久未见 提交于 2019-12-03 03:21:02

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.

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

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