我有一个模块,它遍历对象的公共属性(使用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
// ...
}
但是这个解决方案似乎有点混乱且容易出错......)
答案 0 :(得分:4)
List<PropertyInfo> ignoredList = ...
ignoredList.Add(typeof(TestClass).GetProperty("Prop2"));
应该做的工作......只需检查是否ignoredList.Contains(propinfo)
答案 1 :(得分:0)
您是否可以向属性添加属性以定义应如何使用它们?例如
class TestClass
{
public int Prop1 { get; set; }
[Ignore]
public int Prop2 { get; set; }
}