How do I create a copy of a class object without any reference? ICloneable makes a copy of a class object (via shallow copy) but doesn't support deep copying. I am looking for a function that is smart enough to read all members of a class object and make a deep copy to another object without specifying member names.
-
2possible duplicate of Clone Whole Object Graphxanatos– xanatos2011-10-14 13:39:22 +00:00Commented Oct 14, 2011 at 13:39
-
1Quick and dirty solution is to serialize the object and immediately deserialize to another object. Of course that depends upon whether the object can be properly serialized...canon– canon2011-10-14 13:42:25 +00:00Commented Oct 14, 2011 at 13:42
Add a comment
|
2 Answers
I've seen this as a solution, basically write your own function to do this since what you said about ICloneable not doing a deep copy
public static T DeepCopy(T other)
{
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, other);
ms.Position = 0;
return (T)formatter.Deserialize(ms);
}
}
I'm referencing this thread. copy a class, C#
Comments
public static object Clone(object obj)
{
object new_obj = Activator.CreateInstance(obj.GetType());
foreach (PropertyInfo pi in obj.GetType().GetProperties())
{
if (pi.CanRead && pi.CanWrite && pi.PropertyType.IsSerializable)
{
pi.SetValue(new_obj, pi.GetValue(obj, null), null);
}
}
return new_obj;
}
You can adjust to your needs. For example,
if (pi.CanRead && pi.CanWrite &&
(pi.PropertyType == typeof(string) ||
pi.PropertyType == typeof(int) ||
pi.PropertyType == typeof(bool))
)
{
pi.SetValue(new_obj, pi.GetValue(obj, null), null);
}
OR
if (pi.CanRead && pi.CanWrite &&
(pi.PropertyType.IsEnum || pi.PropertyType.IsArray))
{
...;
}