The following editor will bring you an articleC#Using reflection to implement the deep copy method of object. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor to take a look.
Implementation method
It is very labor-intensive to copy the sub-objects at once by listing them one by one. If the sub-object is a reference type, you also need to consider whether to further copy the sub-object.
In actual applications, if a class has dozens of sub-objects, copying them one by one is boring and time-consuming for developers.
So use the reflection mechanism to achieve it.
But if it is run on the server, it is still recommended to implement it manually.
After all, the reflection mechanism is slower than writing it directly.
Code:
public static class DeepCopyHelper { public static object Copy(this object obj) { Object targetDeepCopyObj; Type targetType = obj.GetType(); //值类型 if (targetType.IsValueType == true) { targetDeepCopyObj = obj; } //引用类型 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 { 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; } }
The above is the detailed content of C# uses reflection to implement deep copy of object sample code sharing. For more information, please follow other related articles on the PHP Chinese website!