合并两个对象数据

本文关键字:两个 对象 数据 合并 | 更新日期: 2023-09-27 18:35:32

我有一个类:

class MyClass {
  public string Text1 { get; set; }
  public string Text2 { get; set; }
  public string Text3 { get; set; }
}

还有两个对象:

var obj1 = new MyClass {Text1 = "Test1", Text2 = "Test2", Text3 = "Test3"};
var obj2 = new MyClass {Text3 = "Another Test"};

我想合并(覆盖 obj1 数据)这些对象,因此结果将是:

mergedObj => {Text1 = "Test1", Text2 = "Test2", Text3 = "Another Test"};

我有很多课程。所以我想要一个方法,用于所有这些对象,该方法获取一个类的两个对象并返回结果。我怎样才能实现这一点?

合并两个对象数据

这将起作用,但它并不涵盖所有情况(仅复制公共属性,没有索引属性):

    class MyClass
    {
        public string Text1 { get; set; }
        public string Text2 { get; set; }
        public string Text3 { get; set; }
        public int Int1 { get; set; }
    }
    public static void Test()
    {
        var obj1 = new MyClass {Text1 = "Test1", Text2 = "Test2", Text3 = "Test3", Int1 = 0};
        var obj2 = new MyClass {Text3 = "Another Test", Int1 = 1};
        var obj3 = MergeObjects(obj1, obj2);
    }
    public static T MergeObjects<T>(T obj1, T obj2)
    {
        var objResult = Activator.CreateInstance(typeof(T));
        var allProperties = typeof(T).GetProperties().Where(x => x.CanRead && x.CanWrite);
        foreach (var pi in allProperties)
        {
            object defaultValue;
            if (pi.PropertyType.IsValueType)
            {
                defaultValue = Activator.CreateInstance(pi.PropertyType);
            }
            else
            {
                defaultValue = null;
            }
            var value = pi.GetValue(obj2, null);
            if (value != defaultValue)
            {
                pi.SetValue(objResult, value, null);
            }
            else
            {
                value = pi.GetValue(obj1, null);
                if (value != defaultValue)
                {
                    pi.SetValue(objResult, value, null);
                }
            }
        }
        return (T)objResult;
    }