How to Clone Objects

后端 未结 13 1263
北海茫月
北海茫月 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:04

    What you are looking is for a Cloning. You will need to Implement IClonable and then do the Cloning.

    Example:

    class Person() : ICloneable
    {
        public string head;
        public string feet; 
    
        #region ICloneable Members
    
        public object Clone()
        {
            return this.MemberwiseClone();
        }
    
        #endregion
    }
    

    Then You can simply call the Clone method to do a ShallowCopy (In this particular Case also a DeepCopy)

    Person a = new Person() { head = "big", feet = "small" };
    Person b = (Person) a.Clone();  
    

    You can use the MemberwiseClone method of the Object class to do the cloning.

提交回复
热议问题