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

发布于 2024-07-16 00:21:08 字数 179 浏览 6 评论 0原文

作为我的应用程序的一部分,我有一个接收 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

清浅ˋ旧时光 2024-07-23 00:21:09

编译器不是在编译时将所有扩展方法都切​​换为静态方法调用吗?

myList.First();

如果

Enumerable.First(myList);

是这种情况,则 .net 运行时(您正在反映的位置)中没有扩展方法。

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

风流物 2024-07-23 00:21:08

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

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

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);
花桑 2024-07-23 00:21:08

基于

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

昨迟人 2024-07-23 00:21:08

这看起来与之前的问题非常相似,可能值得一看。 建议使用 查找类和方法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.

只是我以为 2024-07-23 00:21:08

如果您知道正在从实例获取 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文