【问题标题】:Reflecting constant properties/fields in .net [duplicate]反映.net中的常量属性/字段[重复]
【发布时间】:2009-08-20 20:08:34
【问题描述】:

我有一个如下所示的类:

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

基本上它试图反映自己。我知道如何反映领域一和二。但是我怎么知道它是不是一个常数呢?

【问题讨论】:

  • 我收回了...我找不到字段一和二。
  • 它们不仅仅是字段,它们是静态字段,而不是实例字段。

标签: c# .net reflection constants


【解决方案1】:

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

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

编辑:DataDink 没错,使用 IsLiteral 更流畅

【讨论】:

  • 嗯,是的,意识到它为时已晚......是的,任何 const 本质上也是静态的吗?
  • DataDink 的回答其实更流畅一点。是的;尝试添加 && info.IsStatic。
  • 如果 IsLiteral 和 IsStatic 都为真,那么两者之间的区别是什么?
  • 嗯。 . .某些东西可以是静态的,但不是恒定的。
  • 详细地说,在程序初始化时设置的常量永远不会改变任何独立的对象实例,所以它也可能是静态的,因为没有两个实例会有不同的值。但是,静态的东西不一定需要是常量(字面量),因为它的值可能会在程序的整个生命周期中发生变化。有意义吗?
【解决方案2】:

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

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

与检查属性相比,这为您节省了少量代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    • 2012-02-05
    • 2011-06-19
    • 2011-11-08
    相关资源
    最近更新 更多