用序列化把Object变成字串。

来源:互联网 发布:淘宝账号取消手机绑定 编辑:程序博客网 时间:2024/05/22 15:05
这里是一个例子,如何把一个可以序列化的对象序列化生一个字串。
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);//转成base64string 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!");}}}}


 

原创粉丝点击