c# - 比较同一类的 2 个对象

标签 c# compare

最近,我遇到了在 C# 中比较同一类的 2 个对象的问题。我需要知道更改了哪些字段/属性。

例子如下:

SampleClass 
{
  string sampleField1;
  int sampleField2;
  CustomClass sampleField3; 
}

例如,我有 2 个 SampleClass 对象,object1object2。 这 2 个对象有一些不同的字段值。

  • 谁能知道获取哪些字段不同的最佳方法?

  • 以及如何获取不同字段/属性的(字符串)名称?

  • 我听说过 .Net 中的反射。这是这种情况下的最佳方法吗?
  • 如果我们没有 CustomClass 字段呢? (我只是为了更通用的方法而创建这个字段,我的情况下不存在该字段)

最佳答案

如果你想要通用的方式来获取所有改变的属性

你可以用这个方法(而且是用反射^_^)

    public List<string> GetChangedProperties(object obj1, object obj2)
    {
        List<string> result = new List<string>();

        if(obj1 == null || obj2 == null )
            // just return empty result
            return result;

        if (obj1.GetType() != obj2.GetType())
            throw new InvalidOperationException("Two objects should be from the same type");

        Type objectType = obj1.GetType();
          // check if the objects are primitive types
        if (objectType.IsPrimitive || objectType == typeof(Decimal) || objectType == typeof(String) )
            {
                // here we shouldn't get properties because its just   primitive :)
                if (!object.Equals(obj1, obj2))
                    result.Add("Value");
                return result;
            }

        var properties = objectType.GetProperties();

        foreach (var property in properties)
        {
            if (!object.Equals(property.GetValue(obj1), property.GetValue(obj2)))
            {
                result.Add(property.Name);
            }
        }

        return result;

    }

请注意,此方法仅获取 Primitive type properties已更改并引用引用同一实例的类型属性

编辑: 添加验证以防 obj1obj2 是原始类型 (int,string ...) 因为我试图通过字符串对象,它会报错 还修复了检查两个值是否 equal

的错误

关于c# - 比较同一类的 2 个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31858359/

相关文章:

c# - ASP.Net MVC 3 Razor Response.Write 位置

ios - 如何将用户的当前位置与其他位置进行比较并显示在 UITableView 中?

Mysql更新表1与表2的比较

c# - 随机化对象的位置放置

c# - 从 .Net 应用程序打开 Python 脚本命令窗口时,如何保持打开状态?

c# - 阻止 System.Net.IPAddress 类中的混合 IPv6 格式

c# - 从 C# 中的对象成员获取友好描述

ios - 如何比较两个对象数组?

list - 如何对列表中的元素使用递归?

bash - 'diff' 命令可以忽略不同类型的换行符吗?