|
/****
*
* HCloner v0.1 (C) 2009 by HAKGERSoft
* www.hakger.org
*
*/
using System;
using System.Reflection;
namespace HAKGERSoft {
public class HCloner {
public static T DeepCopy<T>(T obj) {
if(obj==null)
throw new ArgumentNullException("Object cannot be null");
return (T)Process(obj);
}
static object Process(object obj) {
if(obj==null)
return null;
Type type=obj.GetType();
if(type.IsValueType || type==typeof(string)) {
return obj;
}
else if(type.IsArray) {
Type elementType=Type.GetType(type.FullName.Replace("[]",string.Empty));
var array=obj as Array;
Array copied=Array.CreateInstance(elementType,array.Length);
for(int i=0; i<array.Length; i++) {
copied.SetValue(Process(array.GetValue(i)),i);
}
return Convert.ChangeType(copied,obj.GetType());
}
else if(type.IsClass) {
object toret=Activator.CreateInstance(obj.GetType());
FieldInfo[] fields=type.GetFields(BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance);
foreach(FieldInfo field in fields) {
object fieldValue=field.GetValue(obj);
if(fieldValue==null)
continue;
field.SetValue(toret,Process(fieldValue));
}
return toret;
}
else
throw new ArgumentException("Unknown type");
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.