【问题标题】:How to refer to a property of a class (not an object)?如何引用类的属性(不是对象)?
【发布时间】:2012-06-27 16:10:06
【问题描述】:

我有一个模块,它遍历对象的公共属性(使用 Type.GetProperties()),并对这些属性执行各种操作。但是,有时应该以不同方式处理某些属性,例如忽略。例如,假设我有以下类:

class TestClass
{
  public int Prop1 { get; set; }
  public int Prop2 { get; set; }
}

现在,我希望能够指定每当我的模块获取类型为 TestClass 的对象时,应该忽略属性 Prop2。理想情况下,我希望能够这样说:

ReflectionIterator.AddToIgnoreList(TestClass::Prop2);

但这显然行不通。我知道如果我首先创建一个类的实例,我可以获得一个 PropertyInfo 对象,但是仅仅为此创建一个人工实例似乎是不正确的。有没有其他方法可以获取 TestClass::Prop2 的 PropertyInfo 对象?

(作为记录,我当前的解决方案使用字符串文字,然后将其与迭代的每个属性进行比较,如下所示:

ReflectionIterator.AddToIgnoreList("NamespaceName.TestClass.Prop2");

然后在遍历属性时:

foreach (var propinfo in obj.GetProperties())
{
  if (ignoredProperties.Contains(obj.GetType().FullName + "." + propinfo.Name))
    // Ignore
  // ...
}

但这个解决方案似乎有点凌乱且容易出错......)

【问题讨论】:

    标签: c# reflection properties


    【解决方案1】:
    List<PropertyInfo> ignoredList = ...
    
    ignoredList.Add(typeof(TestClass).GetProperty("Prop2"));
    

    应该做的工作......只需检查ignoredList.Contains(propinfo)

    【讨论】:

    • 顺便说一句,有什么办法可以避免字符串?以便编译器和智能感知能够帮助我?
    【解决方案2】:

    您能否向属性添加属性以定义它们应该如何使用?例如

    class TestClass
    {
      public int Prop1 { get; set; }
    
      [Ignore]
      public int Prop2 { get; set; }
    }
    

    【讨论】:

    • 好建议,我可能最终会朝这个方向发展。但是,目前我不确定我是否可以控制我可能获得的每个对象,因此我可能无法添加属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多