动态变量是否有理由不支持扩展方法?有办法避免这种情况吗?
这里是一个例子:
我没有忘记持有我正在使用的扩展方法的类的using指令:
using System.Linq;
此代码可以正常工作:
IEnumerable<string> ie = new HashSet<string>() { "test" };
Console.WriteLine(ie.ToList()[0]);
这个抛出异常:
IEnumerable<string> ie = new HashSet<string>() { "test" };
Console.WriteLine(((dynamic)ie).ToList()[0]);
''System.Collections.Generic.HashSet'不包含'ToList'的定义]
Linq的ToList
期望编译时-IEnumerable
。通过使用dynamic
,您可以完全隐藏编译时类型,并使编译器无法推断正确的方法。因此,您依赖于运行时绑定。
现在,扩展方法只是static
方法的语法糖:
static class Enumerable
{
public static List<T> ToList(IEnumerable<T> e) { ...}
}
您会这样称呼:
Enumerable.ToList(myHashSet);
这也是编译器所做的。它将所有对hashSet.ToList()
的呼叫转换为Enumerable.ToList(hashSet)
。
此方法与您的实际类-哈希集无关-因为扩展方法不modify现有类。他们只是定义似乎就像添加到类一样的方法。或者换句话说:在运行时-这是dynamic
的评估时间-没有HashSet.ToList
这样的方法,但是Enumerable.ToList
。