Using reflection to check if a method is “Extension Method”

家住魔仙堡 提交于 2019-11-28 09:06:21
Brian

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

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:

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

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

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