c# – 如何比较两个对象之间的属性
发布时间:2020-12-15 08:28:41 所属栏目:百科 来源:网络整理
导读:我有两个类似的类:Person,PersonDto public class Person { public string Name { get; set; } public long Serial { get; set; } public DateTime Date1 { get; set; } public DateTime? Date2 { get; set; }} 安培; public class PersonDto{ public strin
我有两个类似的类:Person,PersonDto
public class Person { public string Name { get; set; } public long Serial { get; set; } public DateTime Date1 { get; set; } public DateTime? Date2 { get; set; } } &安培; public class PersonDto { public string Name { get; set; } public long Serial { get; set; } public DateTime Date1 { get; set; } public DateTime? Date2 { get; set; } } 我有两个由两个值相等的对象. var person = new Person { Name = null,Serial = 123,Date1 = DateTime.Now.Date,Date2 = DateTime.Now.Date }; var dto = new PersonDto { Name = "AAA",Date2 = DateTime.Now.Date }; 我需要通过反射检查两个类中所有属性的值.我的最终目标是定义此属性的差异值. IList diffProperties = new ArrayList(); foreach (var item in person.GetType().GetProperties()) { if (item.GetValue(person,null) != dto.GetType().GetProperty(item.Name).GetValue(dto,null)) diffProperties.Add(item); } 我这样做了,但结果并不令人满意.结果的diffProperties计数是4,但我的期望数是1. 当然,所有属性都可以具有空值. 我需要一个通用的解决方案. 解决方法
如果你想通过反射坚持比较,你不应该使用!=(引用相等性,这将使大多数比较失败的GetProperty调用的盒装结果),而是使用
static Object.Equals method.
示例如何使用Equals方法比较反射代码中的两个对象. if (!Object.Equals( item.GetValue(person,null),dto.GetType().GetProperty(item.Name).GetValue(dto,null))) { diffProperties.Add(item); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |