DataRow的序列化问题

人头马1742

人头马1742

2016-01-29 13:23

DataRow的序列化问题,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
{
///
/// Field 的摘要说明。
///

[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; } }}
展开更多 50%)
分享

猜你喜欢

DataRow的序列化问题

电脑网络
DataRow的序列化问题

序列化FastReport

编程语言 网络编程
序列化FastReport

s8lol主宰符文怎么配

英雄联盟 网络游戏
s8lol主宰符文怎么配

J2SE中的序列化之接受默认序列化

编程语言 网络编程
J2SE中的序列化之接受默认序列化

深入理解Java对象的序列化与反序列化的应用

编程语言 网络编程
深入理解Java对象的序列化与反序列化的应用

lol偷钱流符文搭配推荐

英雄联盟 网络游戏
lol偷钱流符文搭配推荐

谈谈J2SE中的序列化之接受默认序列化

编程语言 网络编程
谈谈J2SE中的序列化之接受默认序列化

谈谈J2SE中的序列化之当序列化遭遇继承

编程语言 网络编程
谈谈J2SE中的序列化之当序列化遭遇继承

lolAD刺客新符文搭配推荐

英雄联盟
lolAD刺客新符文搭配推荐

《真三国无双Next》白金攻略(含双人共斗全S)

《真三国无双Next》白金攻略(含双人共斗全S)

Flash MX2004入门与进阶实例——绘图基础(15)

Flash MX2004入门与进阶实例——绘图基础(15)
下拉加载更多内容 ↓