反映.net中的常量属性/字段

时间:2009-08-20 20:08:35

标签: c# .net reflection constants

我有一个如下所示的课程:

public class MyConstants
{
    public const int ONE = 1;
    public const int TWO = 2;

    Type thisObject;
    public MyConstants()
    {
        thisObject = this.GetType();
    }

    public void EnumerateConstants()
    {
        PropertyInfo[] thisObjectProperties = thisObject.GetProperties(BindingFlags.Public);
        foreach (PropertyInfo info in thisObjectProperties)
        {
            //need code to find out of the property is a constant
        }
    }
}

基本上它正试图反思自己。我知道如何反映字段ONE,&二。但我如何知道它是否是常数?

2 个答案:

答案 0 :(得分:16)

那是因为他们是田地,而不是财产。尝试:

    public void EnumerateConstants() {        
        FieldInfo[] thisObjectProperties = thisObject.GetFields();
        foreach (FieldInfo info in thisObjectProperties) {
            if (info.IsLiteral) {
                //Constant
            }
        }    
    }

编辑:DataDink是正确的,使用IsLiteral更顺畅

答案 1 :(得分:5)

FieldInfo对象实际上有很多“IsSomething”布尔值:

var m = new object();
foreach (var f in m.GetType().GetFields())
if (f.IsLiteral)
{
    // stuff
}

无论如何,除了检查属性外,还可以节省很少的代码。