Sometimes a Cloned object is just something you really need. Sometimes you don't want any references to ANYTHING. But Cloning is painful if you have complex types. Here's my fool-proof technique. The only thing to note is that it EXPECTS to operate against a [DataContract]. If you do not control the class definition and cannot inherit from it, then you need to use another method. In most of my coding, it's the DTO I want to clone, so this limitation doesn't come up. Here's the method I like most:using System;
using System.Runtime.Serialization;
using System.IO;
namespace ConsoleApplication1
{
[DataContract]
public class TestClass { }
class Program
{
static void Main(string[] args)
{
var x = Copy(new TestClass());
Console.WriteLine(x.ToString());
}
static T Copy<T>(T o)
{
var _Serial = new DataContractSerializer(typeof(T));
using (var _Stream = new MemoryStream())
{
_Serial.WriteObject(_Stream, o);
_Stream.Position = 0;
return (T)_Serial.ReadObject(_Stream);
}
}
}
}
Reference: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx
0 comments:
Post a Comment