c# - 如何比较两个对象之间的属性

标签 c# reflection

我有两个相似的类:PersonPersonDto

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/

相关文章:

c# - Unity3D C# Button Sprite 交换 - 在运行时附加图像

c# - 非托管资源和 Dispose()

c# - Scriban - 列出解析的表达式(变量)

c# - WiX:在卸载时正确删除非空的临时文件和文件夹

java - 有什么方法可以从反射中获取 Class 吗?

java - Android 创建自定义注释

c# - 如何动态确定类型是否是使用反射的接口(interface)?

c# - 为什么我的控制台应用程序有命令历史记录?

java - 什么时候使用反射是一种好的做法?

c# - 查找枚举成员