Will the dynamic keyword in C#4 support extension methods?

旧时模样 提交于 2019-12-27 11:45:40

问题


I'm listening to a talk about C#4's dynamic keyword and I'm wondering... Will this feature be orthogonal to other .NET features, for example will it support extension methods?

public static class StrExtension {
    public static string twice(this string str) { return str + str; }
}
...
dynamic x = "Yo";
x.twice(); // will this work?

Note: This question was asked before C#4 was shipped which is why it's phrased in the future tense.


回答1:


From the "New Features in C# 4" word doc:

Dynamic lookup will not be able to find extension methods. Whether extension methods apply or not depends on the static context of the call (i.e. which using clauses occur), and this context information is not currently kept as part of the payload.




回答2:


This works which I find interesting at least...

public static class StrExtension
{
   public static string twice(this string str) { return str + str; }
}

...
dynamic x = "Yo";
StrExtension.twice(x);

Still, if the compiler can find the correct extension method at compile time then I don't see why it can't package up a set of extension methods to be looked up at runtime? It would be like a v-table for non-member methods.

EDIT:

This is cool... http://www2.research.att.com/~bs/multimethods.pdf




回答3:


It can't work, Extension methods work depending on having the namespace included in the file and, as far as I know, MSIL has no idea about files and including namespaces.




回答4:


You can create an extension method for object and assign it to a dynamic:

public static void MyExt(this object o) {
    dynamic d = o;
    d.myProp = "foo";
}

and call it like this:

ClassWithMyProp x;
x.MyExt();


来源:https://stackoverflow.com/questions/258988/will-the-dynamic-keyword-in-c4-support-extension-methods

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