繁体   English   中英

如何过滤一个类的属性集合?

[英]How to filter a class properties collection?

示例:我有这个课

public class MyClass
{
    private string propHead;
    private string PropHead { get; set; }

    private int prop01;
    private int Prop01 { get; set; }

    private string prop02;
    private string Prop02 { get; set; }

    // ... some more properties here

    private string propControl;
    private string PropControl { get; }  // always readonly
}

我需要排除propHead和propControl。 要排除propControl:

MyClass mc = new MyClass();
PropertyInfo[] allProps = mc.GetType().GetProperties().Where(x => x.CanWrite).ToArray();

现在,当所有人都享有同等的可访问性时,我该如何排除propHead? 有什么方法可以向propHead添加特殊属性,从而让我从其他属性中排除它。 每个类的属性名称总是不同的。

任何建议将不胜感激。

这将是最简单的方法:

MyClass mc = new MyClass();
PropertyInfo[] allProps = mc.GetType()
    .GetProperties()
    .Where(x => x.Name != "propHead" && x.Name != "propControl")
    .ToArray();

但是,如果您正在寻找更通用的解决方案,可以尝试一下

public class CustomAttribute : Attribute
{
    ...
}

MyClass mc = new MyClass();
PropertyInfo[] allProps = mc.GetType()
    .GetProperties()
    .Where(x => x.GetCustomAttributes(typeof(CustomAttribute)).Length > 0)
    .ToArray();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM