这里是一个例子,如何把一个可以序列化的对象序列化生一个字串。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!");
}
}
}
}
用序列化把Object变成字串。
最新推荐文章于 2024-07-24 09:05:49 发布
本文介绍了一个C#中序列化对象为字符串的例子。通过使用BinaryFormatter将自定义类'helloworld'实例化并序列化到MemoryStream中,再转换为Base64字符串。之后演示了如何从该字符串反序列化回原始对象。
部署运行你感兴趣的模型镜像
您可能感兴趣的与本文相关的镜像
ACE-Step
音乐合成
ACE-Step
ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言
1435

被折叠的 条评论
为什么被折叠?



