首頁  >  文章  >  後端開發  >  C#中序列化實作深拷貝與DataGridView初始化刷新的方法介紹

C#中序列化實作深拷貝與DataGridView初始化刷新的方法介紹

黄舟
黄舟原創
2017-03-21 11:52:471485瀏覽

下面小編就為大家帶來一篇C#中序列化實作深拷貝,實作DataGridView初始化刷新的方法。小編覺得蠻不錯的,現在就分享給大家,也給大家做個參考。一起跟著小編過來看看吧

winfrom中DataGridView在的單元格在編輯時候會修改它的資料來源的,如果我們遇到這樣一種情景,刷新資料來源到原始狀態,這個時候要麼資料來源的重新取得綁定,要麼透過拷貝一份原始檔的資料再綁定處理,這裡介紹拷貝方式處理。

大致程式碼如下:

#1.目標對需要序列化,並實作ICloneable 介面

[Serializable]
public class DtoColumn : ICloneable2.实现接口方法Clone: 


public object Clone()
{
    using (MemoryStream ms = new MemoryStream(capacity))
    {
      object CloneObject;
      BinaryFormatter bf = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
      bf.Serialize(ms, this);
      ms.Seek(0, SeekOrigin.Begin);      
      CloneObject = bf.Deserialize(ms);       
      ms.Close();
      return CloneObject;
    }
}

3. 透過拷貝一份資料來達到刷新的目的:

private List < dto.DtoColumn > DeepCloneData(List < dto.DtoColumn > rawdata) {
  return rawdata.Select(x = >x.Clone()).Cast < dto.DtoColumn > ().ToList()
}

this.dataGridView1.DoThreadPoolWork(() = >
{
  this.dataGridView1.DataSource = DeepCloneData(CloneInitialColumnData);
  this.dataGridView1.Refresh();
});

以上是C#中序列化實作深拷貝與DataGridView初始化刷新的方法介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn