反射将所有属性排除在基类之外,将特定属性排除在所有其他派生类之外 [英] Reflection exclude all attributes from base class and specific attribute from all other derived classes

查看:47
本文介绍了反射将所有属性排除在基类之外,将特定属性排除在所有其他派生类之外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following base, middle and derived classes below::

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属性.

I need a function that given a type, I need to return DataMemberAttribute attributes for all classes in the hierarchy except for the base.

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

In addition, all IgnoreForAllAttribute attributes should be ignored for all classes in the graph.

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

推荐答案

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

Here's a LINQ sample that assumes DateMemberAttribute and IgnoreForAllAttribute are mutually exclusive

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

还有一个假定属性不是互斥的示例

And a sample assuming the attributes are NOT mutually exclusive

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);
       }
}

这篇关于反射将所有属性排除在基类之外,将特定属性排除在所有其他派生类之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆