Reflecting constant properties/fields in .net [duplicate]

ε祈祈猫儿з 提交于 2020-01-03 08:52:52

问题


I have a class which looks like as follows:

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

Bascially it is trying to reflect itself. I know how to reflect fields ONE, & TWO. But how do I know if it is a constant or not?


回答1:


That's because they're fields, not properties. Try:

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

Edit: DataDink's right, it's smoother to use IsLiteral




回答2:


FieldInfo objects actually have a ton of "IsSomething" booleans right on them:

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

Which saves you a tiny ammount of code over checking the attributes anyways.



来源:https://stackoverflow.com/questions/1308507/reflecting-constant-properties-fields-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!