Skip to content

Instantly share code, notes, and snippets.

@azeitler
Created November 13, 2011 02:14
Show Gist options
  • Save azeitler/1361488 to your computer and use it in GitHub Desktop.
Save azeitler/1361488 to your computer and use it in GitHub Desktop.
C# Method Generation for Deep-Copy of any Class
using System;
using System.Reflection;
public static class CodeUtil {
public static string CreateCopyMethod (Type type) {
return CreateCopyMethod (type, false);
}
public static string CreateCopyMethod (Type type, bool includeProperties) {
string output = string.Format ("public static void Copy{0} (ref {0} source, ref {0} target) {{\n", type.Name);
FieldInfo[] fieldInfoArray = type.GetFields ();
int fieldLines = 0;
string fieldOutput = "";
foreach (FieldInfo fieldInfo in fieldInfoArray) {
if (fieldInfo.IsNotSerialized)
continue;
if (fieldInfo.IsPrivate)
continue;
if (fieldInfo.IsStatic)
continue;
if (fieldInfo.GetCustomAttributes (false).Length > 0)
continue;
fieldOutput += string.Format ("\ttarget.{0} = source.{0};\n", fieldInfo.Name);
fieldLines++;
}
if (fieldLines > 0) {
output += "\t// copy fields\n" + fieldOutput;
}
if (includeProperties) {
int propertyLines = 0;
string propertyOutput = "";
PropertyInfo[] propertyInfoArray = type.GetProperties ();
foreach (PropertyInfo propertyInfo in propertyInfoArray) {
if (!propertyInfo.CanRead)
continue;
if (!propertyInfo.CanWrite)
continue;
propertyOutput += string.Format ("\ttarget.{0} = source.{0};\n", propertyInfo.Name);
propertyLines++;
}
if (propertyLines > 0) {
if (fieldLines > 0)
output += "\n";
output += "\t// copy properties\n" + propertyOutput;
}
}
output += "\n}";
return output;
}
}
using UnityEngine;
using UnityEditor;
public static class CodeUtilUnity {
[MenuItem("Tools/Test: CreateCopyMethod (Transform)")]
public static void TestCreateCopyMethod () {
Debug.Log (CreateCopyMethod (typeof(Transform), true));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment