オブジェクトのDeepCopy
これ以外に何かいい方法があれば、コメント下さい。。。m( _ _ )m
1 using System; 2 using System.Collections.Generic; 3 using System.Collections; 4 using System.Text; 5 6 namespace Test 7 { 8 class CopyClass : ICloneable 9 { 10 public CopyClass(int _x, int _y, int _z) 11 { 12 x = _x; 13 y = _y; 14 z = _z; 15 } 16 public object Clone() 17 { 18 return MemberwiseClone(); 19 } 20 public static List<CopyClass> DeepCopy(List<CopyClass> _Src) 21 { 22 List<CopyClass> _Dst = new List<CopyClass>(); 23 if (_Dst == null || _Src == null) 24 return _Dst; 25 26 _Dst.Clear(); 27 _Src.ForEach( delegate(CopyClass elem){ _Dst.Add( (CopyClass)elem.Clone() ); } ); 28 return _Dst; 29 } 30 public int x, y, z; 31 } 32 class Counter 33 { 34 public static IEnumerable<int> Times(int max) 35 { 36 int i = 0; 37 for( i = 0;i < max;i++ ) 38 yield return i; 39 } 40 } 41 class Program 42 { 43 static void Main(string[] args) 44 { 45 List<CopyClass> Test1 = new List<CopyClass>(); 46 List<CopyClass> Test2 = new List<CopyClass>(); 47 foreach (int cnt in Counter.Times(10)) 48 { 49 CopyClass cp = new CopyClass(cnt,cnt,cnt); 50 Test1.Add(cp); 51 } 52 Console.WriteLine(""); 53 Console.WriteLine("Deep Copy 前"); 54 Console.WriteLine("[Test1]"); 55 Test1.ForEach(delegate(CopyClass val) { Console.WriteLine( 56 val.x.ToString() + ":" + 57 val.y.ToString() + ":" + 58 val.z.ToString() ); 59 } 60 ); 61 62 Console.WriteLine(""); 63 Console.WriteLine("Deep Copy [Test1]->[Test2]"); 64 Test2 = CopyClass.DeepCopy(Test1); 65 66 Console.WriteLine(""); 67 Console.WriteLine("Deep Copy 後"); 68 Console.WriteLine("[Test1]"); 69 70 // 参照チェック!!( 書き換え ) 71 Test2[0].x = 100; 72 Test2[0].y = 101; 73 Test2[0].z = 102; 74 75 Test1.ForEach(delegate(CopyClass val) { 76 Console.WriteLine( 77 val.x.ToString() + ":" + 78 val.y.ToString() + ":" + 79 val.z.ToString() ); 80 } 81 ); 82 Console.WriteLine("[Test2]"); 83 Test2.ForEach(delegate(CopyClass val) { 84 Console.WriteLine( 85 val.x.ToString() + ":" + 86 val.y.ToString() + ":" + 87 val.z.ToString() ); 88 } 89 ); 90 } 91 } 92 }