对什么序列化无关紧要,但是,如果将要被序列化的对象不支持序列化(即使指定了Serializable),那么这个对象一定要实现自定义序列化,还是拿Form来说吧,它是不支持序列化的,那么对它进行如下的修改后就可以被序列化了,其它的类也类似操作:
--------将要被序列化的类,这里以Form为代表--------
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization;
using System.Drawing;
namespace SerializableApp
{
/// <summary>
/// 这里要添加对序列化的支持
/// </summary>
[Serializable]
public class SerializableForm : Form, ISerializable
{
/// <summary>
/// 常规构造函数
/// </summary>
public SerializableForm()
{
}
/// <summary>
/// 反序列化构造函数
/// </summary>
/// <param name= "info "> </param>
/// <param name= "context "> </param>
public SerializableForm(SerializationInfo info, StreamingContext context)
{
this.Name = info.GetString( "Name ");
this.Size = (Size)info.GetValue( "Size ", typeof(Size));
this.Location = (Point)info.GetValue( "Location ", typeof(Point));
}
/// <summary>
/// 自定义序列化方法
/// </summary>
/// <param name= "info "> </param>
/// <param name= "context "> </param>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue( "Name ", this.Name);
info.AddValue( "Size ", this.Size);
info.AddValue( "Location ", this.Location);
}
}
}
--------------对序列化的测试----------------
//为了方便测试定义内存流
MemoryStream ms = new MemoryStream();
BinaryFormatter form = new BinaryFormatter();
Type type = typeof(SerializableForm);
object obj = Activator.CreateInstance(type);
//对对象进行序列化
form.Serialize(ms, obj);
ms.Flush();
//获取流中的数据以便反序列化
byte[] bts = ms.GetBuffer();
//反序列化操作
MemoryStream _ms = new MemoryStream(bts);
//生成反序列化后的对象
object ff = form.Deserialize(_ms);
同理,基本控件如 Button TextBox和继承的用户控件都可以使用此方法序列化!
保存一个序列化的控件或窗口:
public void Save()
{
try
{
Button Data = new Button();
System.IO.Stream StreamWrite;
SaveFileDialog DialogueSauver = new SaveFileDialog();
DialogueSauver.DefaultExt = "ProjectData";
DialogueSauver.Title = "保存工程";
DialogueSauver.Filter = "shape files (*.ProjectData)|*.ProjectData";
if (DialogueSauver.ShowDialog() == DialogResult.OK)
{
if ((StreamWrite = DialogueSauver.OpenFile()) != null)
{
BinaryFormatter BinaryWrite = new BinaryFormatter();
BinaryWrite.Serialize(StreamWrite, data);
StreamWrite.Close();
MessageBox.Show("Done");
}
}
}
catch (Exception ex)
{
MessageBox.Show("Exception:" + ex.ToString(), "Save error:");
}
}
public ProjectData Load()
{
ProjectData data=null;
try
{
System.IO.Stream StreamRead;
OpenFileDialog DialogueCharger = new OpenFileDialog();
DialogueCharger.DefaultExt = "ProjectData";
DialogueCharger.Title = "读取工程";
DialogueCharger.Filter = "frame files (*.ProjectData)|*.ProjectData";
if (DialogueCharger.ShowDialog() == DialogResult.OK)
{
if ((StreamRead = DialogueCharger.OpenFile()) != null)
{
BinaryFormatter BinaryRead = new BinaryFormatter();
Button data = (Button)BinaryRead.Deserialize(StreamRead);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Exception:" + ex.ToString(), "Load error:");
}
return data;
}