用序列化把Object变成字串。

这里是一个例子,如何把一个可以序列化的对象序列化生一个字串。
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!");
			}
		}
	}
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值