这里是一个例子,如何把一个可以序列化的对象序列化生一个字串。
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace TestStr
{
[Serializable] //这个class可以序列化
public class helloworld
{
private int a; //定义一个属性
public int A { //这个属性,只读。
get{return a;}
private set{}
}
public helloworld(int a) //构造函数
{
this.a = a;
}
public int add() //定义一个公开函数。
{
return this.a;
}
}
//测试开始
public class Test
{
public static void Main(String[] args)
{
//建立有个MemoryStream的对象
MemoryStream ms = new MemoryStream();
//建立一个BinaryFormatter对象
BinaryFormatter bf = new BinaryFormatter();
//建立一个我们测试用的对象。
helloworld hw = new helloworld(2);
//现在开始把hw序列号,然后存在ms里。
bf.Serialize(ms, hw);
//转成base64
string str = System.Convert.ToBase64String(ms.ToArray());
//显示一下这个base64字串
Console.Write(str);
try{
//现在开始打开serialization的包
ms.Position=0; //重要。要把因为我一直都是在使用ms变量。指针可能指导最后了。
//转成同类型的类。
helloworld hw2 = (helloworld)bf.Deserialize(ms);
//关闭MemoryStream
ms.Close();
//调用测试对象的函数。
Console.Write(hw2.add().ToString());
}
catch(Exception)
{
Console.Write("Bad!");
}
}
}
}