简体   繁体   English

在C#中使用反射时如何跳过不需要的属性

[英]How to skip unwanted properties when using reflection in C#

I am using reflection to get all the properties from class like this: 我正在使用反射来从类中获取所有属性,如下所示:

var props = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); // todo: cache & filter not-needed props)

var itemStr = string.Join(", ", 
                     props.Select(p => p.GetValue(item, null)?.ToString())
                          .ToArray());

item is object type Person defined like this: item是对象类型Person的定义如下:

public sealed class Person : KnowYourCustomerBase
{
     [DataMember]
     public string Surname { get; set; }

     [DataMember]
     public string FirstName { get; set; }

     [DataMember]
     public string MiddleName { get; set; }

     [DataMember]
     public string Address4 { get; set; }

     [DataMember]
     public string DateOfBirth { get; set; }

     [DataMember]
     public string NationalID { get; set; }

     [DataMember]
     public string Gender { get; set; }
}

How can I edit line of code that's getting all the properties and return them for example all except NationalID? 如何编辑获取所有属性的代码行,并返回它们(例如,除NationalID外的所有属性)?

var toExclude = new HashSet<string>("NationalID", ...);

var props = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).
            Where(property => !toExclude.Contains(property.Name));

Replace ... with the name of the other properties you want to exclude and Enumerable.Where will keep only those not in the collection. 将...替换为要排除的其他属性的名称和Enumerable。此处将仅保留那些不在集合中的属性。

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

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