silverlight中的clone: Deep Clone of a business object: the quick and dirty way

来源:互联网 发布:淘宝推广公司靠谱吗 编辑:程序博客网 时间:2024/06/09 18:35

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/

原创粉丝点击