DataRow的序列化问题
在.net里,DataRow類型的對象是不支持序列化的,那么如果在一個需要序列化的對象中含有DataRow類型的字段該怎么辦呢?呵呵,幸好Datatable是支持序列化的。因此,我們可以自定義序列化的行為,并在序列化和反序列化的時候用Datatable來對DataRow進行包裝和解包。
為了自定義序列化行為,必須實現ISerializable接口。實現這個接口要實現 GetObjectData方法以及在反序列化對象時使用的特殊構造函數。前者的作用是把該對象要封裝的數據加入到系統提供的一個容器中,然后系統會對這些數據進行序列化;后者的作用是把反序列化的數據從容器中取出來,然后顯式的賦值給該對象的某一個字段。
如下例所示,應當注意的代碼用黑體標出。
using System;
using System.Data;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.IO;
using System.Security.Permissions;
namespace phenix.Dl
{
?/// <summary>
?/// Field 的摘要說明。
?/// </summary>
?[Serializable]
?public class Field:ISerializable
?{
??private string name="";
??private DataRow dr=null;
??private string title="";
??private int index=-1;
??public int Index
??{
???get{return this.index;}
???set{this.index=value;}
??}
??public string Title
??{
???get{return this.title;}
???set{this.title=value;}
??}
??public string FieldName
??{
???get{return this.name;}
???set{this.name=value;}
??}
??public DataRow FieldInfo
??{
???get{return this.dr;}
???set{this.dr=value;}
??}
??public Field()
??{
???//
???// TODO: 在此處添加構造函數邏輯
???//
??}
??protected Field(SerializationInfo info, StreamingContext context)//特殊的構造函數,反序列化時自動調用
??{
???this.name=info.GetString("fieldname");
???this.title=info.GetString("fieldtitle");
???this.index=info.GetInt32("fieldindex");
???DataTable dt=info.GetValue("fieldinfo",new DataTable().GetType()) as DataTable;
???this.dr=dt.Rows[0];
??}
??[SecurityPermissionAttribute(SecurityAction.Demand,SerializationFormatter=true)]
??public virtual void GetObjectData(SerializationInfo info, StreamingContext context)//序列化時自動調用
??{
???info.AddValue("fieldname", this.name);
???info.AddValue("fieldtitle", this.title);
???info.AddValue("fieldindex", this.index);
???DataTable dt=this.dr.Table.Clone();?//datarow不能同時加入到兩個DataTable中,必須先克隆一個
???DataRow row=dt.NewRow();
???row.ItemArray=dr.ItemArray;
???
???dt.Rows.Add(row);
???info.AddValue("fieldinfo",dt,dt.GetType());
??}
?
??public override string ToString()
??{
???return this.name;
??}
?}
}
總結
以上是生活随笔為你收集整理的DataRow的序列化问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Repeater控件的分页问题
- 下一篇: ColorMatrix 彩色矩阵