简体   繁体   中英

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".

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?

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

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

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

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.

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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