这是继上篇序列化、反序列化的姊妹篇
自定义序列化、反序列化有两点要求:
- 类要实现System.Runtime.Serialization 命名空间的 ISerializable 接口(当然要有[Serializable]属性)。
- 类要实现两个方法:一、ISerializable 接口的 void GetObjectData(SerializationInfo info, StreamingContext context). 二、要实现一个构造函数 pubic classname(Serializationinfo info, StreamingContext context).
下面主要说明以上两个方法的作用以及给出示例代码:
void GetObjectData(Serializationinfo info, StreamContext context ) 是用来处理要进行序列化的成员,其中info 参数提供各个成员字段信息,可在此时对对象中的成员赋值,调用AddValue()方法。
构造函数是在反序列化时自动调用, 并利用info.GetStirng(GetDecimal )等函数获取值。
自定义类:
[Serializable]
public class Fruit : ISerializable
...{
private string _code;
private string _name;
public string Code
...{
get ...{ return _code; }
set ...{ _code = value; }
}
public string Name
...{
get ...{ return _name; }
set ...{ _name = value; }
}
public Fruit()
...{ }
public Fruit(string code, string name)
...{
this._code = code;
this._name = name;
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
...{
info.AddValue("aname", this._name);
info.AddValue("acode", this._code);
}
public Fruit(SerializationInfo info, StreamingContext context)
...{
this.Name = info.GetString("aname");
this.Code = info.GetString("acode");
}实现:
页面加载时序列化到文件
protected void Page_Load(object sender, EventArgs e)
...{
//序列化
FileStream fs = new FileStream(@"D: fruit.xml", FileMode.OpenOrCreate);
Fruit fruit = new Fruit("0001", "苹果");
XmlSerializer xsl = new XmlSerializer(typeof(Fruit));
xsl.Serialize(fs, fruit);
fs.Close();
}
点击按钮反序列化为对象
protected void Button1_Click(object sender, EventArgs e)
...{
//反序列化
FileStream fs = new FileStream(@"D: ruit.xml", FileMode.OpenOrCreate);
XmlSerializer xsl = new XmlSerializer(typeof(Fruit));
Fruit fruit =(Fruit) xsl.Deserialize(fs);
fs.Close();
Response.Write(fruit.Code + "," + fruit.Name);
}
本文介绍如何通过实现 ISerializable 接口来自定义 C# 中的对象序列化和反序列化过程。通过示例代码展示了如何使用 SerializationInfo 和 StreamingContext 对象来保存和恢复对象状态。
1300

被折叠的 条评论
为什么被折叠?



