How to make a shallow copy of an array?

后端 未结 9 739
梦如初夏
梦如初夏 2020-11-27 22:21

I pass a two-dimensional array as a property to my user control. There I store this values in another two-dimensional array:

int[,] originalValues = this.Met         


        
9条回答
  •  庸人自扰
    2020-11-27 22:53

    IClonable is great but unless you IClonable every type in your top level cloned type, you end up with references, AFAIK.

    Based on that, unless you want to walk the object and clone each object within, this seems the simplest approach.

    It's simple and guarantees a clean break from references of deep objects in the original:

    using Newtonsoft.Json;
    
    private T DeepCopy(object input) where T : class
    {
        var copy = JsonConvert.SerializeObject((T)input); // serialise to string json object
        var output = JsonConvert.DeserializeObject(copy); // deserialise back to poco
        return output;
    }
    

    Usage:

    var x = DeepCopy<{ComplexType}>(itemToBeCloned);
    

    Where ComplexType is anything wanting a break from references.

    It takes any Type in, stringifies it, then de-stringifies to a new copy.

    Best use example: If you've selected a complex type as a result of a lambda query and want to modify the result without affecting the original.

提交回复
热议问题