深拷贝、浅拷贝

浅拷贝:

 类实现ICloneable接口

例如:

class Employee : ICloneable
{
public string ID { get; set; }
public int Age { get; set; }
public Department DepartmentName { get; set; }
//实现ICloneable接口的Clone方法
public object Clone()
{
return this.MemberwiseClone();//浅拷贝
}
}
class Department
{
public string DepartmentName { get; set; }
public Department(string value)
{
DepartmentName = value;
}
public override string ToString()
{
return DepartmentName.ToString();
}
}

这样使用:

Employee emp1 = new Employee()
{
    ID = "cjavapy",
    Age = 20,
    DepartmentName = new Department("develop")
};
Employee emp2 = emp1.Clone() as Employee;//浅拷贝

深拷贝:
1.完全复制对象,不管是否含有嵌套对象

/// <summary>
/// 深度克隆
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public T DeepClone<T>(T source)
{
// Don't serialize a null object, simply return the default for that object
if (Object.ReferenceEquals(source, null))
{
return default(T);
}

var deserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };
var serializeSettings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source, serializeSettings), deserializeSettings);
}

或者使用MessagePackSerializer,需要应用安装MessagePack包

例如:

var mc = new MyClass
{
Age = 19,
FirstName = "he",
LastName = "hu",
};

// call Serialize/Deserialize, that's all.
var bytes = MessagePackSerializer.Serialize(mc);
var mc2 = MessagePackSerializer.Deserialize<MyClass>(bytes);

// you can dump msgpack binary to human readable json.
// In default, MeesagePack for C# reduce property name information.
// [99,"hoge","huga"]
var json = MessagePackSerializer.ConvertToJson(bytes);
Console.WriteLine(json);
var text=MessagePackSerializer.SerializeToJson(mc2);
Console.WriteLine(text);

这是实际测试过的,如果有其他建议,请评论区交流,谢谢

posted @ 2024-04-03 14:55  Seamless  阅读(6)  评论(0编辑  收藏  举报