[英]How to check equality of collection type properties, using reflection in C#
[英]How to skip unwanted properties when using reflection in C#
我正在使用反射来从类中获取所有属性,如下所示:
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是对象类型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; }
}
如何编辑获取所有属性的代码行,并返回它们(例如,除NationalID外的所有属性)?
var toExclude = new HashSet<string>("NationalID", ...);
var props = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).
Where(property => !toExclude.Contains(property.Name));
将...替换为要排除的其他属性的名称和Enumerable。此处将仅保留那些不在集合中的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.