我怎样才能通过reflection来获得一个types的所有常量?

我如何使用reflection获取任何types的所有常量?

虽然这是一个旧的代码:

private FieldInfo[] GetConstants(System.Type type) { ArrayList constants = new ArrayList(); FieldInfo[] fieldInfos = type.GetFields( // Gets all public and static fields BindingFlags.Public | BindingFlags.Static | // This tells it to get the fields from all base types as well BindingFlags.FlattenHierarchy); // Go through the list and only pick out the constants foreach(FieldInfo fi in fieldInfos) // IsLiteral determines if its value is written at // compile time and not changeable // IsInitOnly determine if the field can be set // in the body of the constructor // for C# a field which is readonly keyword would have both true // but a const field would have only IsLiteral equal to true if(fi.IsLiteral && !fi.IsInitOnly) constants.Add(fi); // Return an array of FieldInfos return (FieldInfo[])constants.ToArray(typeof(FieldInfo)); } 

资源

您可以使用generics和LINQ轻松将其转换为更干净的代码:

 private List<FieldInfo> GetConstants(Type type) { FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); return fieldInfos.Where(fi => fi.IsLiteral && !fi.IsInitOnly).ToList(); } 

或者用一行:

 type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy) .Where(fi => fi.IsLiteral && !fi.IsInitOnly).ToList(); 

作为types扩展名:

 public static class TypeExtensions { public static IEnumerable<FieldInfo> GetConstants(this Type type) { var fieldInfos = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); return fieldInfos.Where(fi => fi.IsLiteral && !fi.IsInitOnly); } public static IEnumerable<T> GetConstantsValues<T>(this Type type) where T : class { var fieldInfos = GetConstants(type); return fieldInfos.Select(fi => fi.GetRawConstantValue() as T); } } 

如果你想从目标types中获得特定types的所有常量的 ,这里是一个扩展方法(扩展了这个页面上的一些答案):

 public static class TypeUtilities { public static List<T> GetAllPublicConstantValues<T>(this Type type) { return type .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy) .Where(fi => fi.IsLiteral && !fi.IsInitOnly && fi.FieldType == typeof(T)) .Select(x => (T)x.GetRawConstantValue()) .ToList(); } } 

然后,像这样的class级

 static class MyFruitKeys { public const string Apple = "apple"; public const string Plum = "plum"; public const string Peach = "peach"; public const int WillNotBeIncluded = -1; } 

您可以像这样获取string常量值:

 List<string> result = typeof(MyFruitKeys).GetAllPublicConstantValues<string>(); //result[0] == "apple" //result[1] == "plum" //result[2] == "peach" 

使用property.GetConstantValue()来获取值