使用反射来检查方法是否是“扩展方法”
作为我的应用程序的一部分,我有一个接收 MethodInfo 的函数,并且需要根据该方法是否是“扩展方法”对其执行特定操作。
我检查了 MethodInfo 类,但找不到任何显示该方法是扩展的 IsExtension 属性或标志。
有谁知道如何从方法的 MethodInfo 中找到它?
As part of my application I have a function that receives a MethodInfo and need to do specific operations on it depending if that method is "Extension Method".
I've checked the MethodInfo class and I could not find any IsExtension property or flag that shows that the method is extension.
Does anyone knows how can I find that from the method's MethodInfo?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
编译器不是在编译时将所有扩展方法都切换为静态方法调用吗?
如果
是这种情况,则 .net 运行时(您正在反映的位置)中没有扩展方法。
Doesn't the compiler switch all extension methods into static method calls at compile time?
becomes
If this is the case, then there are no extension methods in the .net runtime (where you are reflecting).
您可以在 MethodInfo 实例上调用 IsDefined 方法,通过检查 ExtensionAttribute 是否应用于该方法来查明这一点:
You can call the IsDefined method on the MethodInfo instance to find this out by checking to see if the ExtensionAttribute is applied to the method:
基于
C# 中的 F# 扩展方法,
编译后的表单上似乎有一个属性。 所以看看该方法是否有这个属性:
http:// /msdn.microsoft.com/en-us/library/system.runtime.compilerservices.extensionattribute.aspx
Based on
F# extension methods in C#
it seems there is an attribute on the compiled form. So see if the method has this attribute:
http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.extensionattribute.aspx
这看起来与之前的问题非常相似,可能值得一看。 建议使用 查找类和方法ExtensionAttribute 听起来像是您所追求的。
This looks very similar to an earlier question, might be worth a look. The suggestion there was to look for classes and methods with the ExtensionAttribute which sounds like what you are after.
如果您知道正在从实例获取
MethodInfo
,则可以轻松检查该方法是否是静态的。 扩展方法只是语法糖,会转换为在实例中传递的静态方法调用。If you know you are getting a
MethodInfo
from an instance, you can easily check if the method is static. Extension methods are just syntactic sugar and get transformed into static method calls passing in the instance.