我有一个班级:
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"};
我有很多课程。所以我想要一个方法,为所有这些方法获取一个类的两个对象并返回结果。我怎么能做到这一点?
答案 0 :(得分:3)
这样可行,但它并不涵盖所有情况(只复制公共属性,没有索引属性):
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;
}