简体   繁体   English

如何获取基类的公共静态方法?

[英]How to get public static method of base class?

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. 我的基类有一个公共静态方法,但是当我调用typeof(TDerived).GetMethods(BindingFlags.Public |BindingFlags.Static )时,我的方法不会被返回。 (TDerived of course inherits in some way from my base class). (当然,TDerived从我的基类以某种方式继承)。 I don't have a reference to my base class at the place of this query. 我没有在此查询的位置引用我的基类。
What am I doing wrong? 我究竟做错了什么?

Use the BindingFlags.FlattenHierarchy flag: 使用BindingFlags.FlattenHierarchy标志:

typeof(TDerived).GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)

It is a documented behavior in the Remarks section for Type.GetMethods(BindingFlags) method. 它是Type.GetMethods(BindingFlags)方法的备注部分中记录的行为

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: 从您的问题中,您的代码将变为:

typeof(TDerived).BaseType.GetMethods(BindingFlags.Public | BindingFlags.Static)
                ^---+---^
                    |
                    +-- add this

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. 如果你想要你自己类型的所有静态方法基本类型,那么请使用@Ondrej 回答的FlattenHierarchy选项,这要好得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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