开发者

Can DTO have basic object level operations like Clone?

开发者 https://www.devze.com 2023-04-02 08:37 出处:网络
I understand DTO\'s strict definition is to serve as container t开发者_Go百科o transport data, it shouldn\'t have any behavior. However, I have faced a situation with a need to clone the DTO, two opti

I understand DTO's strict definition is to serve as container t开发者_Go百科o transport data, it shouldn't have any behavior. However, I have faced a situation with a need to clone the DTO, two options: 1. create a Clone method (ICloneable?) in DTO 2. create generic utility class to clone DTO

I currently use option #2. However, I think #1 is acceptable provided there are no logic in DTO. I would like see if any of you faced a similar situation with DTO that required basic operations like Clone, ToString, especially DTOs that had inheritance. Thanks.


If it is a DTO, it should be designed for serialization - in which case your best option is to serialize it via whatever process it is designed, and rehydrate a clone from there. It is pretty rare that this would be a performance issue.


Clone is an operation that is not very commonly needed. However, should you truly need to clone objects it's perfectly acceptable to implement it directly on the object. This will allow you to access the protected MemberwiseClone feature in relation to ICloneable

Cloning is frequently implemented with MemberwiseClone. See Cannot access protected member 'object.MemberwiseClone()' .

If you need deep graph cloning, look into the BinaryFormatter to clone your object. Or look into changing your model to not expect cloning.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号