C# Type.GetFields()-仅返回“0”;“公共建筑”;领域

C# Type.GetFields()-仅返回“0”;“公共建筑”;领域,c#,.net,reflection,C#,.net,Reflection,我想调用Type.GetFields(),只返回声明为“public const”的字段。到目前为止我有这个 type.GetFields(BindingFlags.Static | BindingFlags.Public) 。。。但这也包括“公共静态”字段。尝试检查是否包括。我还没查过,但听起来不错 (我不认为在对GetFields的单个调用中只能获得常量,但可以通过这种方式过滤返回的结果。)从.NET 4.5开始,您可以这样做 public class ConstTest { pr

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

type.GetFields(BindingFlags.Static | BindingFlags.Public)
。。。但这也包括“公共静态”字段。

尝试检查是否包括。我还没查过,但听起来不错


(我不认为在对
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);
    }
}
我检查过了,看起来fields有所有的私有常量

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