我怎样才能使用反射任何类型的所有常量?
Answer 1:
虽然这是一个旧的代码:
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 determines 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));
}
资源
您可以轻松地将其转换为更清晰的代码使用泛型和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();
Answer 2:
如果你想获得一个特定类型的所有常量的值 ,从目标类型,这里是一个扩展方法(延长一些此页面上的答案):
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();
}
}
然后,像这样一类
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"
Answer 3:
作为类型扩展名:
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);
}
}
Answer 4:
使用property.GetConstantValue()来获取价值
文章来源: How can I get all constants of a type by reflection?