我有两个相似的类: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", Serial = 123, Date1 = DateTime.Now.Date, 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);
}
关于c# - 如何比较两个对象之间的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12067255/