为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

倚天杖 2019-10-19 16:55:33
如何使用反射获取任何类型的所有常量?
查看完整描述

3 回答

?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

虽然这是一个旧代码:


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


查看完整回答
反对 回复 2019-10-19
  • 3 回答
  • 0 关注
  • 790 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信