欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-11-20 14:53:29
现有一个对象(objectA)需要用BinaryFormatter序列化成二进制文件: FileStream fileStream = new FileStream(path,...

现有一个对象(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事件,那么在序列化时,就会出错:
 


.net带事件的对象BinaryFormatter 序列化失败
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;