How to get public static method of base class?

后端 未结 2 1280
时光说笑
时光说笑 2021-01-17 10:23

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.

相关标签:
2条回答
  • 2021-01-17 10:42

    Use the BindingFlags.FlattenHierarchy flag:

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

    It is a documented behavior in the Remarks section for Type.GetMethods(BindingFlags) method.

    0 讨论(0)
  • 2021-01-17 10:55

    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.

    0 讨论(0)
提交回复
热议问题