最近在做项目的时候需要用到ICloneable.不过在c#中无法实现内存拷贝。所以必须要对对象中的每一个属性都进行复制.属性太多的时候.一个个的复制显得非常的麻烦.(尤其是当在子类中。又要必须override重新写上一次父类的属性再加上自己的几个属性,所以显得非常麻烦)As Fellowing:
public class A:ICloneable
{
private int m_a;
public int INTA
{
get
{
return m_a;
}
set
{
m_a = value;
}
}
#region ICloneable Imp
public virtual object Clone()
{
A newA = new A();
newA.INTA = INTA;
return newA;
}
#endregion
}
public class B:B
{
private int m_b;
public int INTB
{
get
{
return m_b;
}
set
{
m_b = value;
}
}
public override object Clone()
{
B newB = new B();
newB.INTA = INTA;
newB.INTB = INTB;
return newB;
}
}
其实可以使用Reflection的策略.这样可以自动的在父类实现一个ICloneable就可以了,而子类无需重载Clone函数
public class A:ICloneable
{
private int m_a;
public int INTA
{
get
{
return m_a;
}
set
{
m_a = value;
}
}
#region ICloneable Imp
public virtual object Clone()
{
Type type = this.GetType();
ConstructorInfo cinfo = type.GetConstructor(new Type[0]);
object newObj = cinfo.Invoke(null);
PropertyInfo[] infos = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (PropertyInfo info in infos)
{
if (info.CanRead)
{
if (info.CanWrite)
{
info.SetValue(newObj, info.GetValue(this, null), null);
}
}
}
return newObj;
}
#endregion
}
public class B:B
{
private int m_b;
public int INTB
{
get
{
return m_b;
}
set
{
m_b = value;
}
}
}
注意:在这个方法里面.默认的把需要重新复制的Field都暴露成可以set和get的attribute。如果没有那么做.可以用Reflection的其他方法获得Private 的Field进行复值. :-)