如何获取基类的公共静态方法?
我的基类有一个公共静态方法,但是当我调用 typeof(TDerived).GetMethods(BindingFlags.Public |BindingFlags.Static) 时,我的方法不会返回。 (TDerived 当然以某种方式从我的基类继承)。我在此查询处没有对我的基类的引用。
我做错了什么?
My base class has a public static method, but when I call typeof(TDerived).GetMethods(BindingFlags.Public |BindingFlags.Static
) my method doesn't get returned. (TDerived of course inherits in some way from my base class). I don't have a reference to my base class at the place of this query.
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
BindingFlags.FlattenHierarchy
标志:这是一个记录的行为在
Type.GetMethods(BindingFlags)
方法的“备注”部分中。Use the
BindingFlags.FlattenHierarchy
flag:It is a documented behavior in the Remarks section for
Type.GetMethods(BindingFlags)
method.如果您想获取直接基类型的所有静态成员,即。只有当前类继承的类的静态方法,那么您也可以通过反射访问它。
根据您的问题,您的代码将变为:
当然,这将仅获取该类型的静态方法。如果您想要自己类型和基类型的所有静态方法,请使用 FlattenHierarchy 选项 @Ondrej 回答了,好多了。
If you want to get hold of all the static members of your direct base type, ie. only the static methods of the class from which the current class inherits, then you can access it through reflection as well.
Your code, from your question, would then become:
Of course, this would only get the static methods of that type. If you want all the static methods of your own type and the base type(s), then go with the FlattenHierarchy option that @Ondrej answered with, much better.