如何通过反射获取类型的所有常量?

如何使用反射获取任何类型的所有常量?



倚天杖
浏览 798回答 3
3回答

人到中年有点甜

虽然这是一个旧代码:private FieldInfo[] GetConstants(System.Type type){&nbsp; &nbsp; ArrayList constants = new ArrayList();&nbsp; &nbsp; FieldInfo[] fieldInfos = type.GetFields(&nbsp; &nbsp; &nbsp; &nbsp; // Gets all public and static fields&nbsp; &nbsp; &nbsp; &nbsp; BindingFlags.Public | BindingFlags.Static |&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // This tells it to get the fields from all base types as well&nbsp; &nbsp; &nbsp; &nbsp; BindingFlags.FlattenHierarchy);&nbsp; &nbsp; // Go through the list and only pick out the constants&nbsp; &nbsp; foreach(FieldInfo fi in fieldInfos)&nbsp; &nbsp; &nbsp; &nbsp; // IsLiteral determines if its value is written at&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp;compile time and not changeable&nbsp; &nbsp; &nbsp; &nbsp; // IsInitOnly determines if the field can be set&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp;in the body of the constructor&nbsp; &nbsp; &nbsp; &nbsp; // for C# a field which is readonly keyword would have both true&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp;but a const field would have only IsLiteral equal to true&nbsp; &nbsp; &nbsp; &nbsp; if(fi.IsLiteral && !fi.IsInitOnly)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; constants.Add(fi);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; // Return an array of FieldInfos&nbsp; &nbsp; return (FieldInfo[])constants.ToArray(typeof(FieldInfo));}资源您可以使用泛型和LINQ轻松将其转换为更清晰的代码:private List<FieldInfo> GetConstants(Type type){&nbsp; &nbsp; FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Public |&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;BindingFlags.Static | BindingFlags.FlattenHierarchy);&nbsp; &nbsp; return fieldInfos.Where(fi => fi.IsLiteral && !fi.IsInitOnly).ToList();}或一行:type.GetFields(BindingFlags.Public | BindingFlags.Static |&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;BindingFlags.FlattenHierarchy)&nbsp; &nbsp; .Where(fi => fi.IsLiteral && !fi.IsInitOnly).ToList();
打开App,查看更多内容
随时随地看视频慕课网APP