1

I have a module that iterates through the public properties of an object (using Type.GetProperties()), and performs various operations on these properties. However, sometimes some of the properties should be handled differently, e.g., ignored. For example, suppose I have the following class:

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

Now, I would like to be able to specify that whenever my module gets an object of type TestClass, the property Prop2 should be ignored. Ideally I would like to be able to say something like this:

ReflectionIterator.AddToIgnoreList(TestClass::Prop2);

but that obviously doesn't work. I know I can get a PropertyInfo object if I first make an instance of the class, but it doesn't seem right to create an artificial instance just to do this. Is there any other way I can get a PropertyInfo-object for TestClass::Prop2?

(For the record, my current solution uses string literals, which are then compared with each property iterated through, like this:

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

and then when iterating over the properties:

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

but this solution seems a bit messy and error-prone...)

4

2 に答える 2

4
List<PropertyInfo> ignoredList = ...

ignoredList.Add(typeof(TestClass).GetProperty("Prop2"));

仕事をするべきです...かどうかを確認してくださいignoredList.Contains(propinfo)

于 2012-06-26T10:49:04.757 に答える
0

プロパティに属性を追加して、それらの使用方法を定義できますか? 例えば

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

  [Ignore]
  public int Prop2 { get; set; }
}
于 2012-06-26T10:51:56.267 に答える