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

发布于 2024-08-02 06:35:35 字数 576 浏览 5 评论 0原文

我有一个类,如下所示:

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, &二。但我怎么知道它是否是一个常数呢?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

妄断弥空 2024-08-09 06:35:35

那是因为它们是字段,而不是属性。尝试:

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

编辑:DataDink是对的,使用IsLiteral更流畅

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

满栀 2024-08-09 06:35:35

FieldInfo 对象实际上有大量的“IsSomething”布尔值:

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

无论如何,这可以为您节省少量检查属性的代码。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文