废话不多,直接上代码。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Test
{
public static class MyExtension
{
public static T MyClone<T>(this T self)
{
var xmlSerializer = new XmlSerializer(typeof(T));
var memoryStream = new MemoryStream();
var xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xmlSerializer.Serialize(xmlTextWriter, self);
memoryStream.Position = 0;
var xmlTextReader = new XmlTextReader(memoryStream);
var newInstance = (T) xmlSerializer.Deserialize(xmlTextReader);
return newInstance;
}
}
}
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Test
{
public static class MyExtension
{
public static T MyClone<T>(this T self)
{
var xmlSerializer = new XmlSerializer(typeof(T));
var memoryStream = new MemoryStream();
var xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xmlSerializer.Serialize(xmlTextWriter, self);
memoryStream.Position = 0;
var xmlTextReader = new XmlTextReader(memoryStream);
var newInstance = (T) xmlSerializer.Deserialize(xmlTextReader);
return newInstance;
}
}
}
到底能拷贝多深,我也不知道。