Type.GetFields() – 仅返回“public const”字段

我想调用Type.GetFields()并只返回声明为“public const”的字段。 到目前为止我有这个…

type.GetFields(BindingFlags.Static | BindingFlags.Public) 

……但这也包括“公共静态”字段。

尝试检查FieldInfo.Attributes是否包含FieldAttributes.Literal 。 我没有检查过,但听起来不错……

(我不认为你只能GetFields的一次调用中获得常量 ,但是你可以过滤那种返回的结果。)

 type.GetFields(BindingFlags.Static | BindingFlags.Public).Where(f => f.IsLiteral); 

从.NET 4.5开始,您可以做到这一点

 public class ConstTest { private const int ConstField = 123; public int GetValueOfConstViaReflection() { var fields = this.GetType().GetRuntimeFields(); return (int)fields.First(f => f.Name == nameof(ConstField)).GetValue(null); } } 

我查了一下,看起来田野里有所有的私人景点。