首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

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

2012-09-04 
C# 引用对象深克隆帮助类//克隆帮助类,可以克隆任意 class 对象[System.Serializable]public class ClongH

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="张三"};

 

}

热点排行