關(guān)于C#的深拷貝的實(shí)現(xiàn)方式:
為東至等地區(qū)用戶提供了全套網(wǎng)頁(yè)設(shè)計(jì)制作服務(wù),及東至網(wǎng)站建設(shè)行業(yè)解決方案。主營(yíng)業(yè)務(wù)為成都做網(wǎng)站、網(wǎng)站制作、東至網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠(chéng)的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會(huì)得到認(rèn)可,從而選擇與我們長(zhǎng)期合作。這樣,我們也可以走得更遠(yuǎn)!
①反射
②反序列化
③表達(dá)式樹(shù)
目前只講解利用反射實(shí)現(xiàn)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 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個(gè)類用于測(cè)試:
寵物類->
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; } } }
測(cè)試代碼:
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(A); _copyA.Name = "Kayer"; _copyA.My_Pet.Name = "旺財(cái)"; 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(); } } }
運(yùn)行結(jié)果: