Object deep copy in Silverlight

☆樱花仙子☆ 提交于 2019-12-02 04:55:46

问题


I was trying to create copy of objects in silverligth 5 where interfaces like IFormatters and IcCloanble do not support. *

My objects are like this: (Note that these obkjects are obtained on deserializing xml): I tried to do copy like this:

    [XmlRoot(ElementName = "component")]
        public class Component
        {
            [XmlElement("attributes")]
            public Attributes Attributes { get; set; } 

            [XmlIgnore]
            public Attributes atrbtOrginal = new Attributes();
            [XmlIgnore]
            public Attributes atrbtCopy{ get; set; }
        }
        public Component()
            {          
                atrbtCopy= atrbtOrginal ;
            } 

Sure it will not work then i got this code on seraching on Google :

 public static class ObjectCopier
    {
        public static T Clone<T>(T source)
        {
            if (!typeof(T).IsSerializable)
            {
                throw new ArgumentException("The type must be serializable.", "source");
            }

            // Don't serialize a null object, simply return the default for that object
            if (Object.ReferenceEquals(source, null))
            {
                return default(T);
            }
            IFormatter formatter = new BinaryFormatter();
            Stream stream = new MemoryStream();
            using (stream)
            {
                formatter.Serialize(stream, source);
                stream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(stream);
            }
        }

    }

And i thought of doing something liek this:

objectOrginal.Clone();.

But the problem in silverligth5 is :

Error   2   The type or namespace name 'BinaryFormatter' could not be found (are you missing a using directive or an assembly reference?)   
Error   1   The type or namespace name 'IFormatter' could not be found (are you missing a using directive or an assembly reference?)

is there any alternative in Silverlight 5 . Please explain in detail. Thanks a lot.


回答1:


Implement the DataContractSerializer attributes (DataContract, DataMember) on your classes and call DatacontractSerializer to serialize it to a MemoryStream, then use it again to serialize out of the MemoryStream to a new instance of the object. By far the easiest to understand, and quite performant too.

Example of class definition :

[DataContract]
class MyClass
{
    [DataMember]
    public int MyValue {get;set;}
    [DataMember]
    public string MyOtherValue {get;set;}
}

The method of cloning from one class instance to another is covered in the Microsoft documentation http://msdn.microsoft.com/en-us/library/ms752244(v=vs.110).aspx



来源:https://stackoverflow.com/questions/25359694/object-deep-copy-in-silverlight

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!