Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Reflection - Base class static fields in Derived type

In C#, when I'm reflecting over a derived type, how come I don't see base classes' static fields?

I've tried both type.GetFields(BindingFlags.Static) and type.GetFields().

like image 351
jameszhao00 Avatar asked Aug 24 '09 23:08

jameszhao00


1 Answers

This is how it works. static members are really non-object-oriented stuff. They are not polymorphic and they really belong to their declaring type and are unrelated to other types in the inheritance hierarchy. For instance, a static initializer for a base class is not required to run before accessing a static member in a derived class.

static members of base classes are not returned unless BindingFlags.FlattenHierarchy is specified:

type.GetFields(BindingFlags.Static 
             | BindingFlags.FlattenHierarchy
             | BindingFlags.Public)
like image 94
mmx Avatar answered Oct 22 '22 00:10

mmx