对象类型/// 源对象/// 赞 踩 话不多说上代码: Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。
C#如何深度克隆对象_c# 克隆对象
/// <summary>
/// 利用序列化进行对象拷贝,要求对象是序列化的
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="item">源对象</param>
/// <returns>克隆对象</returns>
public T Clone<T>(T item) where T : class
{
T result = default(T);
if (null != item)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, item);
ms.Seek(0, SeekOrigin.Begin);
result = bf.Deserialize(ms) as T;
ms.Close();
}
return result;
}
[Serializable]
public class Person
{
public string Name { get; set; }
public string Age { get; set; }
public string Birthday { get; set; }
}
//use
//var pClone=Clone(p);
[Serializable]
public class Person:ICloneable
{
public string Name { get; set; }
public string Age { get; set; }
public string Birthday { get; set; }
//var pClone=p.Clone() as Person;
public object Clone()
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, this);
ms.Seek(0, 0);
object obj = bf.Deserialize(ms);
ms.Close();
return obj;
}
}
public class Person
{
public string Name { get; set; }
public string Age { get; set; }
public string Birthday { get; set; }
public Person Clone()
{
Person p=new Person();
p.Name=this.Name;
p.Age=this.Age;
p.Birthday=this.Birthday;
return p;
}
}
利用json来克隆对象,即object->json->object