C#4中的动态关键字是否支持扩展方法?
-
06-07-2019 - |
题
我 C#4 的动态
关键字的“noreferrer”>听取讲话,我想知道......这个功能是否与其他功能正交。 NET功能,例如它是否支持扩展方法?
public static class StrExtension {
public static string twice(this string str) { return str + str; }
}
...
dynamic x = "Yo";
x.twice(); // will this work?
注意:在C#4发布之前就已经提出了这个问题,这就是为什么它将来会用来表达。
解决方案
动态查找将无法进行 找到扩展方法。是否 扩展方法是否适用取决于 在调用的静态上下文中 (即哪些使用条款发生),和 这个上下文信息不是 目前作为有效载荷的一部分保留。
其他提示
这至少让我觉得有趣......
public static class StrExtension
{
public static string twice(this string str) { return str + str; }
}
...
dynamic x = "Yo";
StrExtension.twice(x);
但是,如果编译器可以在编译时找到正确的扩展方法,那么我不明白为什么它不能打包一组扩展方法以便在运行时查找?对于非成员方法,它就像一个v表。
编辑:
这很酷...... http://www2.research.att。 COM /〜BS / multimethods.pdf
它无法工作,扩展方法的工作取决于文件中包含命名空间,据我所知,MSIL不知道文件和包含命名空间。
您可以为对象创建扩展方法,并将其分配给动态:
public static void MyExt(this object o) {
dynamic d = o;
d.myProp = "foo";
}
并将其称为:
ClassWithMyProp x;
x.MyExt();
不隶属于 StackOverflow