读书人

C# 摘引对象深克隆帮助类

发布时间: 2012-09-04 14:19:30 作者: rapoo

C# 引用对象深克隆帮助类

//克隆帮助类,可以克隆任意 class 对象

[System.Serializable]
public class ClongHelper<T>:ICloneable where T : class
{
public ClongHelper(T obj)
{
this.Data = obj;
}
/// <summary>
/// 待克隆的数据
/// </summary>
public T Data { set; get; }

/// <summary>
/// 克隆一个相同的实例
/// </summary>
/// <returns></returns>
public object Clone()
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, this);
ms.Seek(0, SeekOrigin.Begin);
return bf.Deserialize(ms);
}
}

----- 例:克隆 person 对象

------ Person 对象

public class Person

{

public int UserId{set;get;}

public string Name{set;get;}

}

----- 克隆调用实例

private void Test1()

{

Person oP= new Person(){id=1,Name="张三"};

}

读书人网 >C#

热点推荐