Faster deep cloning

前端 未结 9 741
深忆病人
深忆病人 2020-12-02 13:44

Does anyone want a framework/class which allows me to clone by values .Net objects? I\'m only interested with public read/write properties (namely DataContracts), and I don\

9条回答
  •  清歌不尽
    2020-12-02 14:33

    The CGbR Code Generator can generate an implementation of ICloneable for you. All you need is the nuget package and a partial class definition that implements ICloneable. The generator will do the rest for you:

    public partial class Root : ICloneable
    {
        public Root(int number)
        {
            _number = number;
        }
        private int _number;
    
        public Partial[] Partials { get; set; }
    
        public IList Numbers { get; set; }
    
        public object Clone()
        {
            return Clone(true);
        }
    
        private Root()
        {
        }
    } 
    
    public partial class Root
    {
        public Root Clone(bool deep)
        {
            var copy = new Root();
            // All value types can be simply copied
            copy._number = _number; 
            if (deep)
            {
                // In a deep clone the references are cloned 
                var tempPartials = new Partial[Partials.Length];
                for (var i = 0; i < Partials.Length; i++)
                {
                    var value = Partials[i];
                    value = value.Clone(true);
                    tempPartials[i] = value;
                }
                copy.Partials = tempPartials;
                var tempNumbers = new List(Numbers.Count);
                for (var i = 0; i < Numbers.Count; i++)
                {
                    var value = Numbers[i];
                    tempNumbers[i] = value;
                }
                copy.Numbers = tempNumbers;
            }
            else
            {
                // In a shallow clone only references are copied
                copy.Partials = Partials; 
                copy.Numbers = Numbers; 
            }
            return copy;
        }
    }
    

提交回复
热议问题