copy a class, C#

后端 未结 12 1785
失恋的感觉
失恋的感觉 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:42

    Not any straightforward way that will always work. If your class is [Serializable] or implements ISerializable, you can do a roundtrip serialization to create an identical copy. The same works for [DataContract]

    If you only want a shallow copy, you can try Object.MemberwiseClone(). It's a protected method though, and you can only use it from within the class.

    If you're lucky, the class implements ICloneable and you can just call the Clone() method.

提交回复
热议问题