I was implementing the IEditableObject interface for some entity classes in my current project and I needed a quick and dirty way to do the deep clone of an object, since my entity classes are shared between WCF, WPF and Silverlight (yes I’m one of the guys so crazy to build multi-target applications) I needed a method that could work in all the environments.
In WPF and WCF you can rely on the binary formatter and the serialization (entity classes have to be marked with the Serializable attribute), and use code like this:
In Silverlight you can write something similar and use the DataContractSerializer and the xml serialization:
Due to the restriction of Silverlight the DataContractSerializer has some limitations and they depends if you are using or not the DataContract + DataMember attributes:
- With no attributes you can only serialize types that have a default public constructor with no arguments and all public fields/properties, for example something like:
- Using DataContract + DataMember attribute you can choose what to serialize, you do not need the default constructor anymore, but still you are limited to public fields only…unless you use the InternalsVisibleTo attribute and convert the protected and private fields you want to serialize to internal, the class will look like:
plus you have to tag the assembly that holds the entities and make its internal members visibile to the serializer, since DataContractSerializer resides in the System.Runtime.Serialization you have to mark the assembly with:
1: //needed to allow the serializer to access internal members
2: [assembly: InternalsVisibleTo("System.Runtime.Serialization")]
Then using the Silverlight Unit Testing Framework from Jeff Wilcox, you can write a couple of tests like the following ones to verify that it works.
Naturally using both those methods you incur in performance penalty…but hey…this is the quick and dirty way after all.
http://www.primordialcode.com/index.php/2008/10/18/deep-clone-business-object-quick-dirty/
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/bian-cheng-ji-chu/4101.html