How to Clone Objects

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

    In my opinion, the best way to do this is by implementing your own Clone() method as shown below.

    class Person
    {
        public string head;
        public string feet;
    
        // Downside: It has to be manually implemented for every class
        public Person Clone()
        {
            return new Person() { head = this.head, feet = this.feet };
        }
    }
    
    class Program
    {
        public static void Main(string[] args)
        {
            Person a = new Person() { head = "bigAF", feet = "smol" };
            Person b = a.Clone();
    
            b.head = "notEvenThatBigTBH";
    
            Console.WriteLine($"{a.head}, {a.feet}");
            Console.WriteLine($"{b.head}, {b.feet}");
        }
    }
    

    Output:

    bigAf, smol

    notEvenThatBigTBH, smol

    b is totally independent to a, due to it not being a reference, but a clone.

    Hope I could help!

提交回复
热议问题