欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

.NET 中的深拷貝實(shí)現(xiàn)方法詳解

 更新時(shí)間:2025年04月14日 10:36:50   作者:進(jìn)階的小木樁  
在 .NET 中實(shí)現(xiàn)深拷貝(Deep Copy)有幾種常用方法,深拷貝是指創(chuàng)建一個(gè)新對象,并遞歸地復(fù)制原對象及其所有引用對象,而不僅僅是復(fù)制引用,本文給大家介紹.NET 中的深拷貝實(shí)現(xiàn)方法,感興趣的朋友一起看看吧

在 .NET 中實(shí)現(xiàn)深拷貝(Deep Copy)有幾種常用方法,深拷貝是指創(chuàng)建一個(gè)新對象,并遞歸地復(fù)制原對象及其所有引用對象,而不僅僅是復(fù)制引用。

1. 使用序列化/反序列化

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public static class ObjectCopier
{
    public static T DeepCopy<T>(T obj)
    {
        if (!typeof(T).IsSerializable)
        {
            throw new ArgumentException("The type must be serializable.", nameof(obj));
        }
        if (ReferenceEquals(obj, null))
        {
            return default;
        }
        IFormatter formatter = new BinaryFormatter();
        using (var stream = new MemoryStream())
        {
            formatter.Serialize(stream, obj);
            stream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(stream);
        }
    }
}

2. 使用 JSON 序列化(Newtonsoft.Json 或 System.Text.Json)

// 使用 Newtonsoft.Json
using Newtonsoft.Json;
public static T DeepCopy<T>(T obj)
{
    var json = JsonConvert.SerializeObject(obj);
    return JsonConvert.DeserializeObject<T>(json);
}
// 使用 System.Text.Json (推薦.NET Core 3.0+)
using System.Text.Json;
public static T DeepCopy<T>(T obj)
{
    var json = JsonSerializer.Serialize(obj);
    return JsonSerializer.Deserialize<T>(json);
}

3. 實(shí)現(xiàn) ICloneable 接口(手動實(shí)現(xiàn))

public class MyClass : ICloneable
{
    public int Value { get; set; }
    public MyOtherClass Other { get; set; }
    public object Clone()
    {
        var copy = (MyClass)MemberwiseClone(); // 淺拷貝
        copy.Other = (MyOtherClass)Other.Clone(); // 深拷貝引用類型
        return copy;
    }
}
public class MyOtherClass : ICloneable
{
    public string Name { get; set; }
    public object Clone()
    {
        return MemberwiseClone(); // 淺拷貝(因?yàn)橹挥兄殿愋停?
    }
}

4. 使用 AutoMapper(適用于復(fù)雜對象)

using AutoMapper;
var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<MyClass, MyClass>();
    cfg.CreateMap<MyOtherClass, MyOtherClass>();
});
var mapper = config.CreateMapper();
var copy = mapper.Map<MyClass>(original);

5. 注意事項(xiàng)

  • 序列化方法要求所有相關(guān)類都是可序列化的(有 [Serializable] 特性或可以被 JSON 序列化)
  • 循環(huán)引用可能導(dǎo)致堆棧溢出或序列化異常
  • 性能考慮:對于大型對象圖,序列化方法可能較慢
  • 某些特殊類型(如委托、COM 對象)可能無法正確拷貝

6. 推薦方法

  • 對于簡單對象:使用 JSON 序列化(System.Text.Json 性能較好)
  • 對于復(fù)雜對象圖:考慮實(shí)現(xiàn) ICloneable 或使用 AutoMapper
  • 對于性能敏感場景:考慮手動實(shí)現(xiàn)深拷貝邏輯

選擇哪種方法取決于具體需求、對象復(fù)雜度和性能要求。

到此這篇關(guān)于.NET 中的深拷貝實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān).net深拷貝內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:

相關(guān)文章

最新評論