What is the best way to clone a business object in

2019-04-24 01:43发布

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?

4条回答
地球回转人心会变
2楼-- · 2019-04-24 02:01

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).

查看更多
太酷不给撩
3楼-- · 2019-04-24 02:01

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.

查看更多
混吃等死
4楼-- · 2019-04-24 02:03

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);
        }
    }
查看更多
Root(大扎)
5楼-- · 2019-04-24 02:12

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
查看更多
登录 后发表回答