Deep Copy of a C# Object

后端 未结 4 731
梦毁少年i
梦毁少年i 2020-12-17 00:44

I am working on some code that is written in C#. In this app, I have a custom collection defined as follows:

public class ResultList : IEnumerable&l         


        
4条回答
  •  借酒劲吻你
    2020-12-17 01:00

    Here is something that I needed and wrote, it uses reflection to copy every property (and private ones if specified)

    public static class ObjectCloner
    {
        public static T Clone(object obj, bool deep = false) where T : new()
        {
            if (!(obj is T))
            {
                throw new Exception("Cloning object must match output type");
            }
    
            return (T)Clone(obj, deep);
        }
    
        public static object Clone(object obj, bool deep)
        {
            if (obj == null)
            {
                return null;
            }
    
            Type objType = obj.GetType();
    
            if (objType.IsPrimitive || objType == typeof(string) || objType.GetConstructors().FirstOrDefault(x => x.GetParameters().Length == 0) == null)
            {
                return obj;
            }
    
            List properties = objType.GetProperties().ToList();
            if (deep)
            {
                properties.AddRange(objType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic)); 
            }
    
            object newObj = Activator.CreateInstance(objType);
    
            foreach (var prop in properties)
            {
                if (prop.GetSetMethod() != null)
                {
                    object propValue = prop.GetValue(obj, null);
                    object clone = Clone(propValue, deep);
                    prop.SetValue(newObj, clone, null);
                }
            }
    
            return newObj;
        }
    }
    

提交回复
热议问题