Object copy is often used in programming. The following provides a method for object deep copy, which is quite good.
[Csharp]
Public object Copy (this object obj)
{
Object targetDeepCopyObj;
Type targetType = obj. GetType ();
// Value Type
If (targetType. IsValueType = true)
{
TargetDeepCopyObj = obj;
}
// Reference type
Else
{
TargetDeepCopyObj = System. Activator. CreateInstance (targetType); // create a reference object
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
{
Field. SetValue (targetDeepCopyObj, Copy (fieldValue ));
}
}
Else if (member. MemberType = System. Reflection. MemberTypes. Property)
{
System. Reflection. PropertyInfo myProperty = (System. Reflection. PropertyInfo) member;
MethodInfo info = myProperty. GetSetMethod (false );
If (info! = Null)
{
Object propertyValue = myProperty. GetValue (obj, null );
If (propertyValue is ICloneable)
{
MyProperty. SetValue (targetDeepCopyObj, (propertyValue as ICloneable). Clone (), null );
}
Else
{
MyProperty. SetValue (targetDeepCopyObj, Copy (propertyValue), null );
}
}
}
}
}
Return targetDeepCopyObj;
}
Public object Copy (this object obj)
{
Object targetDeepCopyObj;
Type targetType = obj. GetType ();
// Value Type
If (targetType. IsValueType = true)
{
TargetDeepCopyObj = obj;
}
// Reference type
Else
{
TargetDeepCopyObj = System. Activator. CreateInstance (targetType); // create a reference object
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
{
Field. SetValue (targetDeepCopyObj, Copy (fieldValue ));
}
}
Else if (member. MemberType = System. Reflection. MemberTypes. Property)
{
System. Reflection. PropertyInfo myProperty = (System. Reflection. PropertyInfo) member;
MethodInfo info = myProperty. GetSetMethod (false );
If (info! = Null)
{
Object propertyValue = myProperty. GetValue (obj, null );
If (propertyValue is ICloneable)
{
MyProperty. SetValue (targetDeepCopyObj, (propertyValue as ICloneable). Clone (), null );
}
Else
{
MyProperty. SetValue (targetDeepCopyObj, Copy (propertyValue), null );
}
}
}
}
}
Return targetDeepCopyObj;
}
Author: cangkukuaimanle