Getting a list of constants using Reflection
Thanks to
Drew Marsh I was able to create a function to get a list of the constants for a particular type in c#. There were two key things I was missing:
- BindingFlags.FlattenHierarchy
- Specifies that static members up the hierarchy should be returned. Static members include fields, methods, events, and properties. Nested types are not returned (More on BindingFlags)
- IsInitOnly property of a FieldInfo
- Gets a value indicating whether the field can only be set in the body of the constructor.(More Info)
Anyway here is the function:
private FieldInfo[] GetConstants(System.Type type)
{
ArrayList constants = new ArrayList();
FieldInfo[] fieldInfos = type.GetFields(
BindingFlags.Public | BindingFlags.Static |
BindingFlags.FlattenHierarchy);
foreach(FieldInfo fi in fieldInfos)
if(fi.IsLiteral && !fi.IsInitOnly)
constants.Add(fi);
return (FieldInfo[])constants.ToArray(typeof(FieldInfo));
}PS: Code colorized by a codehtmler that Shawn A Van Ness and I are working, you will see more information about that soon.