How to Clone Objects

后端 未结 13 1176
北海茫月
北海茫月 2020-11-30 04:36

When I do the following.. anything done to Person b modifies Person a (I thought doing this would clone Person b from Person a). I also have NO idea if changing Person a wil

相关标签:
13条回答
  • 2020-11-30 05:07

    Painlessly: Using NClone library

    Person a = new Person() { head = "big", feet = "small" };
    Person b = Clone.ObjectGraph(a); 
    
    0 讨论(0)
  • 2020-11-30 05:07

    It couldn't be simpler than this:

        public SomeClass Clone () {
    
            var clonedJson = JsonConvert.SerializeObject (this);
    
            return JsonConvert.DeserializeObject<SomeClass> (clonedJson);
        }
    

    Just serialize any object to a JSON string and then deserialize it. This will do a deep copy...

    0 讨论(0)
  • 2020-11-30 05:07

    You could do it like this:

    var jss = new JavaScriptSerializer();
    var b = jss.Deserialize<Person>(jss.Serialize(a));
    

    For deep cloning you may want to take a look at this answer: https://stackoverflow.com/a/78612/550975

    0 讨论(0)
  • 2020-11-30 05:09

    a and b are just two references to the same Person object. They both essentially hold the address of the Person.

    There is a ICloneable interface, though relatively few classes support it. With this, you would write:

    Person b = a.Clone();
    

    Then, b would be an entirely separate Person.

    You could also implement a copy constructor:

    public Person(Person src)
    {
      // ... 
    }
    

    There is no built-in way to copy all the fields. You can do it through reflection, but there would be a performance penalty.

    0 讨论(0)
  • 2020-11-30 05:10

    This happens because "Person" is a class, so it is passed by reference. In the statement "b = a" you are just copying a reference to the one and only "Person" instance that you created with the keyword new.

    The easiest way to have the behavior that you are looking for is to use a "value type".

    Just change the Person declaration from

    class Person
    

    to

    struct Person
    
    0 讨论(0)
  • 2020-11-30 05:14

    Since the MemberwiseClone() method is not public, I created this simple extension method in order to make it easier to clone objects:

    public static T Clone<T>(this T obj)
    {
        var inst = obj.GetType().GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
    
        return (T)inst?.Invoke(obj, null);
    }
    

    Usage:

    var clone = myObject.Clone();
    
    0 讨论(0)
提交回复
热议问题