copy a class, C#

后端 未结 12 1763
失恋的感觉
失恋的感觉 2020-12-03 10:13

Is there a way to copy a class in C#? Something like var dupe = MyClass(original).

12条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 10:55

    Yes and no. This is an area where you need to be a bit careful because there are some traps (and then again, it's not difficult).

    First of all, if you poke around in the Base Class Library (BCL) a bit, you may discover the ICloneable interface. Not all types implement this interface, but those that do have a Clone method that will return a new instance of the same type with (presumably) the same values.

    However, herein lies a trap: The ICloneable interface does not sufficiently specify whether a deep clone or a shallow clone is expected, so some implementations do one thing, and other implementations the other. For this reason, ICloneable isn't used much, and its further use is actively being discouraged - see the excellent Framework Design Guidelines for more details.

    If you dig further into the BCL, you may discover that System.Object has the protected MemberwiseClone method. While you can't call this method directly from another type, you can use this method to implement cloning in your own objects.

    A common cloning pattern is to define a protected constructor of the class you want to clone and pass an already existing instance as a parameter. Something like this:

    public class MyClass()
    {
        public MyClass() {}
    
        protected MyClass(MyClass other)
        {
            // Cloning code goes here...
        }
    
        public MyClass Clone()
        {
            return new MyClass(this);
        }
    }
    

    However, that obviously only works if you control the type you wish to clone.

    If you wish to clone a type that you can't modify, and which doesn't provide a Clone method, you will need to write code to explicitly copy each piece of data from the old instance to the new instance.

提交回复
热议问题