溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C# 深拷貝

發布時間:2020-07-23 11:45:09 來源:網絡 閱讀:1849 作者:Aonaufly 欄目:編程語言

關于C#的深拷貝的實現方式:

①反射

②反序列化

③表達式樹

目前只講解利用反射實現C#深拷貝的方法:

深拷貝工具類:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace CopyDemo
{
    public sealed class CopyTools
    {
        public static T DeepCopy<T>(T obj)
        {
            //如果是字符串或值類型則直接返回
            if (obj is string || obj.GetType().IsValueType) return obj;
            object retval = Activator.CreateInstance(obj.GetType());
            FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
            foreach (FieldInfo field in fields)
            {
                try { field.SetValue(retval, DeepCopy(field.GetValue(obj))); }
                catch { }
            }
            return (T)retval;
        }
    }
}

下面2個類用于測試:

寵物類->

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CopyDemo
{
    public sealed class Pet
    {
        public string Name { get; set; }
    }
}

人物類->

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CopyDemo
{
    public sealed class People
    {
        public string Name { set; get; }
        public Pet My_Pet { get; set; }
    }
}

測試代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CopyDemo
{
    public class Program
    {
        static void Main(string[] args)
        {
            People A = new People() {My_Pet = new Pet()};
            A.Name = "Aonaufly";
            A.My_Pet.Name = "小白";
            Console.WriteLine("=================================================");
            People _copyA = CopyTools.DeepCopy<People>(A);
            _copyA.Name = "Kayer";
            _copyA.My_Pet.Name = "旺財";
            Console.WriteLine("源 name : {0} , petName : {1}" , A.Name,A.My_Pet.Name);
            Console.WriteLine("Copy name : {0} , petName : {1}", _copyA.Name, _copyA.My_Pet.Name);
            Console.ReadKey();
        }
    }
}

運行結果:

C# 深拷貝

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女