What is the best way to clone a business object in

2019-04-24 01:31发布

问题:

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.