C# 深拷贝的具体代码的封装与调用

先封装下实现方法:
  public class DeepClone
{
public static object CopyObject(Object obj)
{
if (obj == null)
{
return null;
}
Object targetDeepCopyObj;
Type targetType = obj.GetType(); //zhileixing
if (targetType.IsValueType == true)
{
targetDeepCopyObj = obj;
} //yin yong lei xing
else
{
targetDeepCopyObj = System.Activator.CreateInstance(targetType);
System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers(); foreach (System.Reflection.MemberInfo member in memberCollection)
{
if (member.MemberType == System.Reflection.MemberTypes.Field)
{
System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;
Object fieldValue = field.GetValue(obj); if (fieldValue is ICloneable)
{
field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());
}
else
{
//di gui
field.SetValue(targetDeepCopyObj, CopyObject(fieldValue));
}
}//copy attribute
else if (member.MemberType == System.Reflection.MemberTypes.Property)
{
System.Reflection.PropertyInfo myproperty = (System.Reflection.PropertyInfo)member; MethodInfo info = myproperty.GetSetMethod(false); if (info != null)
{
try
{
Object propertyValue = myproperty.GetValue(obj, null); if (propertyValue is ICloneable)
{
myproperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(),null);
}
else
{
myproperty.SetValue(targetDeepCopyObj, CopyObject(propertyValue), null);
}
}
catch (System.Exception ex)
{ }
}
}
}
}
return targetDeepCopyObj;
}
}
}
具体调用:
   protected void Page_Load(object sender, EventArgs e)
{
User user = new User { name="zkj",age=};
Object obj = DeepClone.CopyObject(user);
}
public class User {
public string name { get; set; }
public int age { get; set; }
}
个人理解:上述深拷贝的方法主要是利用反射的原理遍历对象中的属性,对于值类型和引用类型条件判断(不知道值类型和引用类型的孩纸,可以先去复习下),如果是引用类型就就直接用clone()方法,否则递归CopyObject(Object obj
),对类型的数据简单复制。这里有深拷贝与浅拷贝的实质区别的深入分析(http://www.cnblogs.com/nliao/archive/2012/11/18/2776114.html)
本文源码摘自:http://www.cnblogs.com/fnz0/p/5645527.html
上一篇:启用div作为编辑器 添加contentEditalbe属性


下一篇:Prometheus Node_exporter 之 Network Netstat TCP Linux MIPs