Deep Copy a .NET Class Instance Without Serialization

前端 未结 3 708
轻奢々
轻奢々 2021-02-15 16:33

I am using an instance class from a third-party DLL, and I need to do a deep copy on a particular instance. The class is not marked as Serializable, and therefore

3条回答
  •  广开言路
    2021-02-15 16:58

    You can't (or perhaps shouldn't is what I'm looking for).

    If the class is not designed to be serialized, and it does not provide you a means to clone it (i.e. in the form of a clone or copy method) then you cannot easily automatically do this. (And in addition, if this facility is not provided, then you probably should not do this, as the class is probably not designed with this type of usage in mind.)

    However, if you really want to do it and you're in a full trust environment, then of course you can do some dirty stuff using FormatterServices.GetUninitializedObject and then using reflection to copy the field values from one object to the other. But this is almost certainly a bad idea.

提交回复
热议问题