一直都对这个方法很感兴趣,网上大概看过说是什么深复制浅复制啥的,看的一头雾水。
估计很多人都知道,也会用,当然也不会看。。
于是我为了验证自己的想法,写个简单的测试。
首先写个类,里面加个方法便于看结果:
public class Data
{
public int A { get; set; }
public int B { get; set; }
public int C { get; set; }
public void Print(string title)
{
Console.WriteLine("----- {0} -----", title);
Console.WriteLine("A: {0}", A);
Console.WriteLine("B: {0}", B);
Console.WriteLine("C: {0}", C);
Console.WriteLine();
}
}
有时候需要得到和一个类对象数据一模一样的复制品,刚开始直接加个等号:
Data a = new Data();
a.A = 1;
a.B = 2;
a.C = 3;
a.Print("a");
<strong>Data b = a;</strong>
b.A = 0;
b.B = 1;
b.C = 2;
b.Print("b");
a.Print("a");
这就导致了个啥问题呢,你复制出一份一模一样的数据肯定是为了不影响到被复制的那份数据,结果呢,复制出来的数据里面改一改,原数据也变了,肯定是不行的。
有时候没办法了,就在数据类里加个方法:
public Data Clone()
{
Data newData = new Data();
newData.A = this.A;
newData.B = this.B;
newData.C = this.C;
return newData;
}
但有时候里面属性太多了,懒得写,就偷懒:
public Data Clone() //using System.Reflection;
{
Data newData = new Data();
PropertyInfo[] props = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var prop in props)
{
if (prop.CanRead && prop.CanWrite)
{
prop.SetValue(newData,
prop.GetValue(this, null));
}
}
return newData;
}
但是嘛有时候别人看了会说:你这个方法咋回事啊?赶紧给我删了!我猜十有八九是没看懂>_>
一直都想试试这个所谓“深复制”的,但老是忘。接下来就写对应的测试代码。
首先直接写
Data c = a.MemerwiseC
发现点不出来。于是乎去MSDN查:
Object.MemberwiseClone Method ()
结果发现是个受保护方法。
protected object MemberwiseClone()
Return Value
Type: System.ObjectA shallow copy of the current Object.
只能在类内部调用,那么就写在刚才那个Clone方法里好了: public Data Clone()
{
return (Data)this.MemberwiseClone();
}
然后测试:
Data a = new Data();
a.A = 1;
a.B = 2;
a.C = 3;
a.Print("a");
Data b = a;
b.A = 0;
b.B = 1;
b.C = 2;
b.Print("b");
a.Print("a");
a.A = 1;
a.B = 2;
a.C = 3;
b.Print("b");
Data c = a.Clone();
c.Print("c");
a.A = 0;
a.B = 1;
a.C = 2;
a.Print("a");
b.Print("b");
c.Print("c");
结果: