对象序列化生成字符串,反序列化
2012-06-01 10:17 我就是我O(∩_∩)O~ 阅读(380) 评论(0) 编辑 收藏 举报可以使用属性(Attribute)将类的元素标为可序列化的(Serializable)和不可被序列化的(NonSerialized)。.NET中有两个类实现了IFormatter借口的类中的Serialize和Deserialize方法:BinaryFormatter和SoapFormatter。这两个类的区别在于数据流的格式不同 。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
namespace WindowsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//把类序列化生成字符串
private void button1_Click(object sender, EventArgs e)
{
//实例化类
MyObject _object = new MyObject();
_object.Name = textBox1.Text; //为名称赋值
_object.Value = textBox2.Text; //为值赋值
//实例化二制进的实例
IFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream(); //定一个内存流
formatter.Serialize(stream, _object); //序列化后放到流中
byte[] _byte = stream.ToArray(); //得到字节数组
string str = Convert.ToBase64String(_byte); //转为字符串
stream.Close(); //关闭内存流
richTextBox1.Text = str; //显示到文本框中
}
//把序列化的字符串反序列化生成对象
private void button2_Click(object sender, EventArgs e)
{
string str = richTextBox1.Text; //得到保存的序列化的字符串
byte[] _byte = Convert.FromBase64String(str); //转换为字符数组
MemoryStream stream = new MemoryStream(_byte); //放到内存流中
IFormatter _formatter = new BinaryFormatter(); //
MyObject _object = (MyObject)_formatter.Deserialize(stream); //反序列化转换成对象
stream.Close(); //关闭内存流
textBox3.Text = _object.Name; //显示类中的名称
textBox4.Text = _object.Value; //显示类中的值
richTextBox2.Text = _object.ToString();
}
//把对象序列化生成xml字符串
private void button3_Click(object sender, EventArgs e)
{
MyObject _object = new MyObject();
_object.Name = textBox1.Text;
_object.Value = textBox2.Text;
//实例化xml序列化对象,注意:引用命名空间System.Runtime.Serialization.Formatters.Soap;
IFormatter formatter = new SoapFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, _object);
byte[] _byte = stream.ToArray();
string str = Convert.ToBase64String(_byte);
stream.Close();
richTextBox1.Text = str;
}
//把序列化的xml字符串反序列化生成对象
private void button4_Click(object sender, EventArgs e)
{
string str = richTextBox1.Text;
byte[] _byte = Convert.FromBase64String(str); //
MemoryStream stream = new MemoryStream(_byte);
IFormatter _formatter = new SoapFormatter(); //
MyObject _object = (MyObject)_formatter.Deserialize(stream);
stream.Close();
textBox3.Text = _object.Name;
textBox4.Text = _object.Value;
richTextBox2.Text = _object.ToString();
}
}
//序列化的类
[Serializable]
public class MyObject
{
private string _Name = string.Empty;
private string _Value = string.Empty;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
public string Value
{
get { return _Value; }
set { _Value = value; }
}
}
}
转:http://blog.csdn.net/chenwenlin/article/details/1901967