Created
November 13, 2011 02:14
-
-
Save azeitler/1361488 to your computer and use it in GitHub Desktop.
C# Method Generation for Deep-Copy of any Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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