gpt4 book ai didi

c# - 合并两个对象数据

转载 作者:太空宇宙 更新时间:2023-11-03 23:45:30 28 4
gpt4 key购买 nike

我有一个类(class):

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"};

我有很多课。所以我想要一个方法来获取一个类的两个对象并返回结果。我怎样才能做到这一点?

最佳答案

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

    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;
}

关于c# - 合并两个对象数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27675675/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com