简体   繁体   English

使用反射检查方法是否为“扩展方法”

[英]Using reflection to check if a method is "Extension Method"

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".作为我的应用程序的一部分,我有一个接收 MethodInfo 的函数,需要根据该方法是否为“扩展方法”对其进行特定操作。

I've checked the MethodInfo class and I could not find any IsExtension property or flag that shows that the method is extension.我检查了 MethodInfo 类,但找不到任何表明该方法是扩展的IsExtension属性或标志。

Does anyone knows how can I find that from the method's MethodInfo?有谁知道我如何从方法的 MethodInfo 中找到它?

您可以在 MethodInfo 实例上调用IsDefined方法,通过检查ExtensionAttribute是否应用于该方法来找出这一点:

bool isExtension=someMethod.IsDefined(typeof(ExtensionAttribute),true);

Based on基于

F# extension methods in C#C# 中的 F# 扩展方法

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 http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.extensionattribute.aspx

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.那里的建议是寻找带有ExtensionAttribute 的类和方法,这听起来像您所追求的。

If you know you are getting a MethodInfo from an instance, you can easily check if the method is static.如果您知道从实例获取MethodInfo ,则可以轻松检查该方法是否是静态的。 Extension methods are just syntactic sugar and get transformed into static method calls passing in the instance.扩展方法只是语法糖,并转换为传入实例的静态方法调用。

Doesn't the compiler switch all extension methods into static method calls at compile time?编译器不会在编译时将所有扩展方法切换为静态方法调用吗?

myList.First();

becomes变成

Enumerable.First(myList);

If this is the case, then there are no extension methods in the .net runtime (where you are reflecting).如果是这种情况,则 .net 运行时(您正在反射的地方)中没有扩展方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM