首先輸出的是多少?
class Program { static void Main(string[] args) { Test a = new Test() { Age =12, Name= "aaa" }; Test b = a; b.Name ="bbb"; Console.WriteLine(a.Name); Console.ReadKey(); } } class Test { public int Age { get; set; } public string Name { get; set; } }
應該是bbb,個人理解是因為是引用類型的緣故,指針指向了b,所以輸出的是bbb。
如果要 有一個b,它和a的內容完全一樣,a的值不變。
大體有三種方法:
1,一個一個屬性的賦值。
2,用struct 代替class.
3,用反射加泛型實現深拷貝。
/* 利用反射實現深拷貝*/ public static object DeepCopy(object _object) { Type T = _object.GetType(); object o = Activator.CreateInstance(T); PropertyInfo[] PI = T.GetProperties(); for (int i = 0; i < PI.Length; i++) { PropertyInfo P = PI[i]; P.SetValue(o, P.GetValue(_object)); } return o; } }
使用的時候 Test b = (Test)DeepCopy(a);
