Type.GetMethod(string,BindingFlags)是不是将标志视为标志? [英] Is Type.GetMethod(string, BindingFlags) not treating the flags as flags?

查看:80
本文介绍了Type.GetMethod(string,BindingFlags)是不是将标志视为标志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从已知具有公共静态方法foobar的任意对象开始,我已经看到这两种形式都将找到该方法。

 obj.GetType()。GetMethod(< span class =code-string>  foobar
obj.GetType()。GetMethod( foobar,BindingFlags.Static | BindingFlags.Public)。

但这两种形式都返回null。

 obj.GetType()。GetMethod(  foobar ,BindingFlags.Static)
obj.GetType()。GetMethod( foobar,BindingFlags.Public)

Type.GetMethod 的此签名的MS描述告诉我所有四个都应该找到该方法。它看起来像是一个实现错误。我是对的吗?

解决方案

如果您只传递 Public 或<$,感觉代码应该有用c $ c>静态,文档明确指出它不会:



您必须指定 Instance Static 以及公共 NonPublic 或不会退回任何会员。


这里没有任何车,经过多次测试。你标记 BindingFlags.Static | BindingFlags.Public 表示获取该类型的所有方法(在您的情况下,匹配指定的简单名称),这些方法同时是静态和公共的。这个方法确实可以返回null。如果发生这种情况,则意味着没有方法符合这些标准。检查。



请注意以下
  • 在代码示例中,忽略(抛出)方法返回的结果;
  • 名称区分大小写。




祝你好运,

-SA

Starting with an arbitrary object that is known to have a public static method "foobar", I have seen that both these forms will find the method.

obj.GetType().GetMethod("foobar")
obj.GetType().GetMethod("foobar", BindingFlags.Static | BindingFlags.Public).

But these two forms both return null.

obj.GetType().GetMethod("foobar", BindingFlags.Static)
obj.GetType().GetMethod("foobar", BindingFlags.Public)

The MS description of this signature for Type.GetMethod tells me that all four should find that method. It looks like an implementation error to me. Am I right?

解决方案

Whilst it feels like the code should work if you only pass Public or Static, the documentation clearly states that it won't:


You must specify Instance or Static along with Public or NonPublic or no members will be returned.


There is nothing buggy here, tested too many times. You flag BindingFlags.Static | BindingFlags.Public means getting all methods of the type (in you case, matching specified simple name) which are static and public at the same time. This method can really return null. If it happens, it means that no methods meet these criteria. Check it up.

Note the following
  • In your code sample, you ignore (throw out) result returned by the method;
  • Names are case-sensitive.


Good luck,
—SA


这篇关于Type.GetMethod(string,BindingFlags)是不是将标志视为标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆