What is the best way to clone a business object in Silverlight?

限于喜欢 提交于 2020-01-02 02:46:06

问题


What is the best way to create a clone of a DTO? There is not an ICloneable interface or a BinaryFormatter class in Silverlight. Is reflection the only way?


回答1:


Here is the code we came up with for cloning. This works in Silverlight 2 & 3.

Public Shared Function Clone(Of T)(ByVal source As T) As T
    Dim serializer As New DataContractSerializer(GetType(T))
    Using ms As New MemoryStream
        serializer.WriteObject(ms, source)
        ms.Seek(0, SeekOrigin.Begin)
        Return DirectCast(serializer.ReadObject(ms), T)
    End Using
End Function



回答2:


ICloneable is not available in Silverlight 4(I don't know about 1/2/3 or upcoming version) . It is removed from Silverlight 4's public APIs. Help from Mike Schall code; it is working for me.

public LayerDto Clone(LayerDto source)
    {

        DataContractSerializer serializer = new DataContractSerializer(typeof(LayerDto));
        using (MemoryStream ms = new MemoryStream())
        {
            serializer.WriteObject(ms, source);
            ms.Seek(0, SeekOrigin.Begin);
            return (LayerDto)serializer.ReadObject(ms);
        }
    }



回答3:


How to create clone if my source is IEnumerable. This LayerDto also has some object type(eg MetaItemDto).

Code :

public class LayerDto { }
public class MetaItemDtoList : System.Collections.ObjectModel.ObservableCollection { }

public static IEnumerable Clone(IEnumerable source)

{

        IEnumerable<LayerDto> layers;

        DataContractSerializer serializer = new DataContractSerializer(typeof(IEnumerable<LayerDto>));
        using (MemoryStream ms = new MemoryStream())
        {
            serializer.WriteObject(ms, source);
            ms.Seek(0, SeekOrigin.Begin);
            //return (IEnumerable<LayerDto>)serializer.ReadObject(ms);
            layers = (IEnumerable<LayerDto>)serializer.ReadObject(ms);
            return layers;
        }

}

but what is problem I am facing is that layer doesn't show it's metaItems(for every layer).




回答4:


I believe the standard cloning functionality was left out to keep it simple and lightweight. I believe you could use either JSON or XML serialization to achieve the same thing though. Not sure about the performance costs though.



来源:https://stackoverflow.com/questions/202699/what-is-the-best-way-to-clone-a-business-object-in-silverlight

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