Created
December 10, 2014 00:24
-
-
Save cameronism/90df247375dfd79e98d2 to your computer and use it in GitHub Desktop.
Slow .NET Object Cloner
This file contains hidden or 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
| public static class SlowCloner | |
| { | |
| public static T Clone<T>(T val, int depth = 64) | |
| { | |
| return (T)CloneNonGeneric(val, typeof(T), depth); | |
| } | |
| static object CloneNonGeneric(object val, Type type, int depth = 64) | |
| { | |
| if (val == null) return null; | |
| switch (Type.GetTypeCode(type)) | |
| { | |
| case TypeCode.Object: | |
| return CloneObject(val, type, depth); | |
| default: | |
| // all the other typecodes are immutable anyway | |
| return val; | |
| } | |
| } | |
| static object CloneObject(object val, Type type, int depth) | |
| { | |
| var fields = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); | |
| var clone = FormatterServices.GetUninitializedObject(type); | |
| foreach (var fi in fields) | |
| { | |
| fi.SetValue(clone, CloneNonGeneric(fi.GetValue(val), fi.FieldType, depth - 1)); | |
| } | |
| return clone; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment