关于深浅克隆
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace test
{
public delegate void aa(heihei a);
class Class15
{
static void Main( string [] args)
{
heihei a = new heihei()
{
id = " 1 "
};
aa aa = new aa(test2);
IAsyncResult ar = aa.BeginInvoke(a, null , null );
Thread.Sleep( 3000 );
a.id = " 2 " ;
test3(a);
aa.EndInvoke(ar);
Console.ReadLine();
}
private static void test2(heihei a)
{
Console.WriteLine( " test2 " );
Console.WriteLine(a.id);
Thread.Sleep( 10000 );
Console.WriteLine(a.id);
}
private static void test3(heihei a)
{
Console.WriteLine( " test3 " );
Console.WriteLine(a.id);
}
}
public class heihei
{
public string id { get ; set ; }
}
}
我一直都是用深克隆,因为虽然简单类可能只有值类型,但是指不定什么时候就有个引用类型。深克隆目前来说比较实在的方法是序列化加反序列化,当然你也可以自己使用反射,或者一个对一个的赋值。我一般都是自己做一个方法比如叫DeepCopy().
我一直知道.net好像提供了什么Clone()还有什么MemberwiseClone(),提供了一些克隆相关的东东,但是没有弄清楚,今天有时间就看了一下,原来.net提供了一个ICloneable接口,该接口下有一个Clone()方法,你可以实现它用来实现你自己的克隆方式,比如深克隆或是浅克隆,MemberwiseClone()是object类中的一个方法,用来实现类的浅克隆,这个是.net提供的现成方法,不过大多数时候它应该没有什么用处,我们需要自己实现自己的深克隆.
.net提供了一个ICloneable接口只是为我们方法名约定,用这个来Clone方法来表示类的克隆机制,它并没有提供什么有建设性的东东。我们使用名为 DeepCopy一样可以,只是如果大家都用它,可能就会成为一种约定熟成。OK,以后我就用Clone作为我的类的深克隆的名称。
这里给一个使用MemberwiseClone()实现浅克隆结合异步编程的例子,
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace test.test
{
public delegate void aa(heihei a);
class Class16
{
static void Main( string [] args)
{
heihei a = new heihei()
{
id = " 1 "
};
aa aa = new aa(test2);
IAsyncResult ar = aa.BeginInvoke(a, null , null );
heihei c = a.Clone() as heihei;
c.id = " 2 " ;
test3(c);
aa.EndInvoke(ar);
Console.ReadLine();
}
private static void test2(heihei a)
{
Console.WriteLine( " test2 " );
Console.WriteLine(a.id);
Thread.Sleep( 10000 );
Console.WriteLine(a.id);
}
private static void test3(heihei a)
{
Console.WriteLine( " test3 " );
Console.WriteLine(a.id);
}
}
public class heihei:ICloneable
{
public string id { get ; set ; }
public object Clone()
{
return MemberwiseClone();
}
}
}
c2,c1均指向同一个引用,