Deep Copy using Reflection in an Extension Method for Silverlight?

后端 未结 3 1153
再見小時候
再見小時候 2020-12-17 05:38

So I\'m trying to find a generic extension method that creates a deep copy of an object using reflection, that would work in Silverlight. Deep copy using serialization is no

3条回答
  •  不思量自难忘°
    2020-12-17 06:02

    Can't you just use regular .NET reflection? Serialize your object to a MemoryStream and then deserialize it back. This will create a deep copy (ultimately using reflection) and will require hardly any code on your part:

    T DeepCopy(T instance)
    {
      BinaryFormatter formatter=new BinaryFormatter();
    
      using(var stream=new MemoryStream())
      {
        formatter.Serialize(stream, instance);
        stream.Position=0;
    
        return (T)formatter.Deserialize(stream);
      }
    }
    

提交回复
热议问题