可以使用Json序列化和反序列化来解决该问题。在模型类中实现一个复制方法,使用JsonConvert进行序列化和反序列化。例如:
using Newtonsoft.Json;
public class MyModel
{
public int Id { get; set; }
public string Name { get; set; }
public List Numbers { get; set; }
public void CopyFrom(MyModel other)
{
// Serialize the other object to a string
string json = JsonConvert.SerializeObject(other);
// Deserialize the string to this object
JsonConvert.PopulateObject(json, this);
}
}
这段代码定义了一个包含泛型列表的MyModel
类,并在其中实现了一个CopyFrom
方法,该方法接受另一个MyModel
对象作为参数,并使用Json序列化和反序列化来将参数对象的所有属性值复制到当前对象上。
使用时,只需要调用CopyFrom
方法即可完成复制:
MyModel model1 = new MyModel { Id = 1, Name = "AAA", Numbers = new List { 1, 2, 3 } };
MyModel model2 = new MyModel { Id = 2, Name = "BBB", Numbers = new List { 4, 5, 6 } };
model1.CopyFrom(model2);