![](/img/trans.png)
[英]Type.GetFields return an empty System.Reflection.FieldInfo array for public fields
[英]Type.GetFields() - only returning “public const” fields
我想调用Type.GetFields()并只返回声明为“public const”的字段。 到目前为止我有这个...
type.GetFields(BindingFlags.Static | BindingFlags.Public)
......但这也包括“公共静态”字段。
type.GetFields(BindingFlags.Static | BindingFlags.Public).Where(f => f.IsLiteral);
尝试检查FieldInfo.Attributes
是否包含FieldAttributes.Literal
。 我没有检查过,但听起来不错......
(我不认为你只能在一次调用GetFields
获得常量 ,但你可以过滤那种返回的结果。)
从.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);
}
}
我查了一下,看起来田野里有所有的私人景点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.