關于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();
}
}
}