110,536
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 通过内存序列化的办法克隆一个对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static T MemoryClone<T>(T t) where T : class //已测试
{
System.IO.MemoryStream stream = new System.IO.MemoryStream();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize(stream, t);
stream.Position = 0; //stream.Seek(0, SeekOrigin.Begin);
return formatter.Deserialize(stream) as T;
}
[Serializable]
class hehe<T> : EventArgs where T : class
{
public int a { get; set; }
public int b { get; set; }
public T Clone()
{
return MemoryClone<T>(this as T);
}
}
[Serializable]
class hehe1 : hehe<hehe1>
{
public int c { get; set; }
}
hehe1 newobj = new hehe1().Clone();
public static class CloneExtention
{
public static T MemoryClone<T>(T t) where T : class //已测试
{
System.IO.MemoryStream stream = new System.IO.MemoryStream();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize(stream, t);
stream.Position = 0; //stream.Seek(0, SeekOrigin.Begin);
return formatter.Deserialize(stream) as T;
}
public static T Clone<T>(this T t) where T : hehe
{
return MemoryClone(t);
}
}