Reflection从所有其他派生类中排除基类的所有属性和特定属性

g18*_*18c 1 .net c# system.reflection

我有以下基础,中间和派生类::

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; }
}
Run Code Online (Sandbox Code Playgroud)

我需要一个给定类型的函数,我需要为层次结构中除基础之外的所有类返回DataMemberAttribute属性.

此外,应该忽略图中所有类的所有IgnoreForAllAttribute属性.

var derivedObject = new MostDerived();
var attributes = MyShinyAttributeFunction(derivedObject.GetType());
// returns [] { ValueMostDerived, ValueMiddle }
Run Code Online (Sandbox Code Playgroud)

Ric*_*der 6

这是一个LINQ示例,它假定DateMemberAttribute和IgnoreForAllAttribute是互斥的

IEnumerable<PropertyInfo> MyProperties(object o)
{
   o.GetType().GetProperties()
    .Where(p => !(p.DeclaringType is Base))
    .Where(p => p.GetCustomAttributes(false).Any(a => a is DataMemberAttribute)
}
Run Code Online (Sandbox Code Playgroud)

并且假设属性的示例不是互斥的

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);
       }
}
Run Code Online (Sandbox Code Playgroud)