博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
.net带事件的对象BinaryFormatter 序列化失败
阅读量:4553 次
发布时间:2019-06-08

本文共 2005 字,大约阅读时间需要 6 分钟。

现有一个对象(objectA)需要用BinaryFormatter序列化成二进制文件:

FileStream fileStream = new FileStream(path, FileMode.Create);BinaryFormatter formatter = new BinaryFormatter();formatter.Serialize(fileStream, objectA);

 

对象objectA的定义如下:

[Serializable()]    public class ObjectA    {        public string Name        { set; get; }       public event EventHandler
Created; }

 

注意:对象ObjectA有一个事件:Created.
如果在不能被序列化的对象(譬如WinForm里面)订阅了ObjectA的Created事件,那么在序列化时,就会出错:
 
对此,我并没有找到很好的解释,就连微软的官方文档里面也只字未提(还是我没有看懂)。
 
 

 给出完整代码:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Runtime.Serialization.Formatters.Binary;using System.IO;namespace BinarySerializer{public partial class Form1 : Form{public Form1(){InitializeComponent();}private void button1_Click(object sender, EventArgs e){SaveFileDialog dialog = new SaveFileDialog();if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK){try{ObjectA objectA = new ObjectA { Name = "A" };if (checkBox1.Checked)objectA.Created += new EventHandler
(objectA_Created);//对象在被序列化时,如果对象的事件被其他对象订阅了,则会出现序列化失败错误,将这句注销就序列化成功。string path = dialog.FileName;FileStream fileStream = new FileStream(path, FileMode.Create);BinaryFormatter formatter = new BinaryFormatter();formatter.Serialize(fileStream, objectA);MessageBox.Show("保存成功");}catch (Exception ex){MessageBox.Show(ex.Message);}}}void objectA_Created(object sender, EventArgs e){throw new NotImplementedException();}}[Serializable()]public class ObjectA{public string Name{ set; get; }public event EventHandler
Created;}}

 

Demo: 解决方案:
在事件上加“  [field: NonSerialized]”标签,就不会再序列化事件了。
http://www.baryudin.com/blog/events-and-binaryformatter-serialization-net.html
http://stackoverflow.com/questions/2308620/why-is-binaryformatter-trying-to-serialize-an-event-on-a-serializable-class
 
 

转载于:https://www.cnblogs.com/deepleo/archive/2013/03/29/2989710.html

你可能感兴趣的文章
LeetCode Maximum Subarray
查看>>
Ubuntu 14.04 更新源
查看>>
kafka生产者与消费者
查看>>
单元测试框架"艾信.NET单元测试工具(AssionUnit)"开发---第二步
查看>>
git 项目最常用命令总结
查看>>
[Arduino] 在串口读取多个字符串,并且转换为数字数组
查看>>
redis-window 集群配置
查看>>
4.1.6 Grundy数-硬币游戏2
查看>>
图像处理的软件
查看>>
Sql 2000系统表 语句查询表结构
查看>>
[CentOS_7.4]Linux编译安装ffmpeg
查看>>
大数据存储平台之异构存储实践深度解读
查看>>
1.2 Stream API
查看>>
Less2css error 终极解决方案
查看>>
DNS服务器的原理
查看>>
django_数据库操作—增、删、改、查
查看>>
django_mysql_配置
查看>>
day 37 并发编程和操作系统的发展史 + 进程
查看>>
面试问题总结
查看>>
python 15 days
查看>>