我在下面有以下基类、中间类和派生类::
public class Base
{
[DataMemberAttribute()]
public int ValueBase { get; set; }
[IgnoreForAllAttribute("Param1", "Param2")]
public int IgnoreBase { get; set; }
}
public class Middle : Base
{
[DataMemberAttribute()]
public int ValueMiddle { get; set; }
[IgnoreForAllAttribute("Param1", "Param2")]
public int IgnoreMiddle { get; set; }
}
public class MostDerived : Middle
{
[DataMemberAttribute()]
public int ValueMostDerived { get; set; }
[IgnoreForAllAttribute("Param1", "Param2")]
public int IgnoreMostDerived { get; set; }
}
我需要一个给定类型的函数,我需要为层次结构中除基类之外的所有类返回 DataMemberAttribute 属性。
此外,图中的所有类都应忽略所有 IgnoreForAllAttribute 属性。
var derivedObject = new MostDerived();
var attributes = MyShinyAttributeFunction(derivedObject.GetType());
// returns [] { ValueMostDerived, ValueMiddle }
最佳答案
这是一个假定 DateMemberAttribute 和 IgnoreForAllAttribute 互斥的 LINQ 示例
IEnumerable<PropertyInfo> MyProperties(object o)
{
o.GetType().GetProperties()
.Where(p => !(p.DeclaringType is Base))
.Where(p => p.GetCustomAttributes(false).Any(a => a is DataMemberAttribute)
}
假设属性不互斥的样本
IEnumerable<PropertyInfo> MyProperties(object o)
{
o.GetType().GetProperties()
.Where(p => !(p.DeclaringType is Base))
.Where(p =>
{
var attributes = p.GetCustomAttributes(false);
return attributes.Any(a => a is DataMemberAttribute)
&& !attributes.Any(a => a is IgnoreForAllAttribute);
}
}
关于c# - 反射排除基类的所有属性和所有其他派生类的特定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12667219/