栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

虽然这是一个旧代码:

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();


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/402879.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号