c# - 反射排除基类的所有属性和所有其他派生类的特定属性

标签 c# .net 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; }
}

我需要一个给定类型的函数,我需要为层次结构中除基类之外的所有类返回 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/

相关文章:

c# - 如何获取 asp.net c# 的发布数据

c# - wpf自定义控件: draggable/resizable rectangle within another rectangle

c# - 如何将 Font 保留在继承的 TextBox 中?

c# - 为用户提供发送未捕获异常错误报告的选项

c# - GenericArguments[0], 'MvcApplication66.Controllers.HomeController+Info' , 在 'System.Nullable` 1[T ]' violates the constraint of type parameter ' T'

c# - 如何在 .NET Core 中发出类型

c# - 从列表转换为字典,foreach 语句有问题

c# - 为什么 DispatcherTimer Tick 事件没有按时发生?

c# - BitConverter 类中 IsLittleEndian 的用例是什么?

c# - 想要在运行时在程序集内加载程序集?