当前位置: 移动技术网 > IT编程>开发语言>.net > .net带事件的对象BinaryFormatter 序列化失败

.net带事件的对象BinaryFormatter 序列化失败

2018年04月10日  | 移动技术网IT编程  | 我要评论

蓟县haobc,曾宝仪跳污水感染,向幸姿

现有一个对象(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<EventArgs> Created;

    }

注意:对象ObjectA有一个事件:Created.如果在不能被序列化的对象(譬如WinForm里面)订阅了ObjectA的Created事件,那么在序列化时,就会出错:
 


带事件的对象序列化失败Demo
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<EventArgs>(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<EventArgs> Created;

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网