C#二进制序列化实例分析
作者:张林春 时间:2022-09-21 01:43:38
本文实例讲述了C#二进制序列化的方法。分享给大家供大家参考。具体如下:
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
namespace WebApplication1.Serialize
{
public partial class Binary1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//二进制序列化不同于 XMLSerializer 类,后者只序列化公共字段。
protected void Button1_Click(object sender, EventArgs e)
{
MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = "Some String";
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("C:/MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
}
[Serializable]
public class MyObject
{
public int n1 = 0;
public int n2 = 0;
public String str = null;
}
protected void Button2_Click(object sender, EventArgs e)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("C:/MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject)formatter.Deserialize(stream);
stream.Close();
// Here's the proof.
Response.Write("n1: {0}"+ obj.n1+"<br/>");
Response.Write("n2: {0}" + obj.n2 + "<br/>");
Response.Write("str: {0}" + obj.str + "<br/>");
}
//上面所用的 BinaryFormatter 非常有效,生成了非常简洁的字节流。
//通过该格式化程序序列化的所有对象也可以通过该格式化程序进行反序列化,这使该工具对于序列化将在 .NET Framework 上被反序列化的对象而言十分理想。
//需要特别注意的是,在反序列化一个对象时不调用构造函数。出于性能方面的原因对反序列化施加了该约束。
//但是,这违反了运行库与对象编写器之间的一些通常约定,开发人员应确保他们在将对象标记为可序列化时了解其后果。
//如果可移植性是必需的,则转为使用 SoapFormatter。
//只需用 SoapFormatter 代替上面代码中的 BinaryFormatter,
//并且如前面一样调用 Serialize 和 Deserialize。此格式化程序为上面使用的示例生成以下输出。
}
}
希望本文所述对大家的C#程序设计有所帮助。
标签:C#,二进制,序列化
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
springboot返回前端中文乱码的解决
2023-08-09 11:49:12
Android实现简单计时器功能
2021-11-22 03:30:00
![](https://img.aspxhome.com/file/2023/6/138586_0s.jpg)
Java实现简易计算器(逆波兰表达式)
2022-06-17 13:48:23
![](https://img.aspxhome.com/file/2023/9/116209_0s.jpg)
详细解读Java的Lambda表达式
2021-12-30 15:32:36
![](https://img.aspxhome.com/file/2023/0/71650_0s.jpg)
Android开发之资源文件用法实例总结
2023-05-13 06:02:39
Java泛型常见面试题(面试必问)
2021-11-20 20:51:55
Mybatis Select Count(*)的返回值类型介绍
2022-06-17 12:51:19
Java毕业设计实战之在线高中考试系统的实现
2021-07-04 06:15:20
![](https://img.aspxhome.com/file/2023/3/71813_0s.jpg)
分享安装Android Studio3.6的经验教训
2021-12-24 07:39:29
![](https://img.aspxhome.com/file/2023/4/137424_0s.png)
浅谈java线程状态与线程安全解析
2023-05-11 19:20:25
![](https://img.aspxhome.com/file/2023/1/132231_0s.png)
Java 回调函数深入理解
2023-11-01 17:32:04
C#3.0中Lambda表达式详解
2023-08-08 04:01:37
C#委托与冒泡排序实例
2022-05-03 13:26:21
C#实现简易点餐功能
2021-10-20 22:14:31
![](https://img.aspxhome.com/file/2023/7/91367_0s.jpg)
JAVA HashMap详细介绍和示例
2023-04-07 00:17:43
![](https://img.aspxhome.com/file/2023/2/88742_0s.jpg)
解析C#编程的通用结构和程序书写格式规范
2022-12-22 03:41:41
详解C#中的定时器Timer类及其垃圾回收机制
2021-07-21 10:57:39
基于Java信号量解决死锁过程解析
2023-05-13 22:23:02
springboot使用AOP+反射实现Excel数据的读取
2022-12-10 05:25:55
![](https://img.aspxhome.com/file/2023/0/83450_0s.png)
Android实现手机游戏隐藏虚拟按键
2023-01-29 02:04:55