Submitted by Thomas on Sat, 2006-10-14 09:38.
Here is a C# class that can create a deep copy clone of an arbitrary object. The thing that's special about it is that it should work for any class that extends it, so that you don't need to re-write a custom clone() function for every child class (as it seems the C# framework creators would like). This does a deep copy so be careful about members that recursively include one another.
Another way of doing this would be to use serialization . . . I just personally thought the reflection package would be more elegant.
///
/// Class for data which can be cloned.
///
public class THData
{
///
/// Function for doing a deep clone of an object.
///
/// Returns a deep-copy clone of the object.
public virtual THData DeepClone()
{
//First do a shallow copy.
THData returnData = (THData)this.MemberwiseClone();
//Get the type.
Type type = returnData.GetType();
//Now get all the member variables.
FieldInfo[] fieldInfoArray = type.GetFields();
//Deepclone members that extend THData.
//This will ensure we get everything we need.
foreach (FieldInfo fieldInfo in fieldInfoArray)
{
//This gets the actual object in that field.
object sourceFieldValue = fieldInfo.GetValue(this);
//See if this member is THData
if (sourceFieldValue is THData)
{
//If so, cast as a THData.
THData sourceTHData = (THData)sourceFieldValue;
//Create a clone of it.
THData clonedTHData = sourceTHData.DeepClone();
//Within the cloned containig class.
fieldInfo.SetValue(returnData, clonedTHData);
}
}
return returnData;
}
}
Deep Copy Clone of an
Its very helpful for me and
I tried the code and its
Really its a
I have an object that
what would be nice is if you
ArrayList
ArrayList
Fieldinfo
It's been a while since I wrote this, but I believe it's a structure for accessing class members anonymously - i.e. it lets you get both the name and the value of the class members when you don't know either. Not exactly speedy but nevertheless a useful thing to have in certain situations.
Sounds good, but what is the
Sounds good, but what is the FieldInfo[]?