为什么BinaryFormatter的尝试序列化的Serializable类的事件? [英] Why is BinaryFormatter trying to serialize an Event on a Serializable class?

查看:207
本文介绍了为什么BinaryFormatter的尝试序列化的Serializable类的事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个标记为可序列化一个简单的类,它恰好有一个事件。我试图为事件成员作为非序列化,但是编译器会抱怨。然而,当我去序列化类的实例,该BinaryFormatter的抛出一个异常,该事件是不可序列化。这是否意味着你不能序列化有事件的类?如果是这样,那么编译器应该这么说了前面。

 流文件= File.open方法(F,FileMode.Open);
BinaryFormatter的BF =新的BinaryFormatter();

obj对象= NULL;
尝试
{
    OBJ = bf.Deserialize(文件);
}
赶上(System.Runtime.Serialization.SerializationException E)
{
    的MessageBox.show(反序列化失败:{0},e.Message);
}
file.Close();

System.Collections.ArrayList节点列表= OBJ为System.Collections.ArrayList;

的foreach(在节点列表树节点的节点)
{
    treeView.Nodes.Add(节点);
}
 

无法工作,对下面的类:

  [序列化()]
类简单
{
    私人诠释敏;
    私人字符串myString的;
    公共事件SomeOtherEventDefinedElsewhere TheEvent;
 

}

解决方案
  

在事件的情况下,还必须   添加字段属性修饰词时,   运用非序列化属性   使得特性应用于   底层代表,而不是   事件本身     高级序列化 - MSDN


preFIX的 NonSerializedAttribute 与现场

  [字段:非序列化]
公共事件MyEventHandler MyEvent;
 

I have a simple class that is marked as Serializable, and it happens to have an event. I tried to mark the event member as NonSerialized, however the compiler complains. Yet when I go to serialize the class instance, the BinaryFormatter throws an exception that the event is non serializable. Does that mean you can't serialize classes that have events? If so, then the compiler should say so up front.

Stream file = File.Open("f", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();

object obj = null;
try
{
    obj = bf.Deserialize(file);
}
catch (System.Runtime.Serialization.SerializationException e)
{
    MessageBox.Show("De-Serialization failed : {0}", e.Message);
}
file.Close();

System.Collections.ArrayList nodeList = obj as System.Collections.ArrayList;

foreach (TreeNode node in nodeList)
{
    treeView.Nodes.Add(node);
}

Fails to work on the following class:

[Serializable()]
class Simple
{
    private int myInt;
    private string myString;
    public event SomeOtherEventDefinedElsewhere TheEvent;

}

解决方案

"In the case of events, you must also add the field attribute qualifier when applying the NonSerialized attribute so that the attribute is applied to the underlying delegate rather than to the event itself" Advanced Serialization - MSDN


Prefix the NonSerializedAttribute with field

[field:NonSerialized]
public event MyEventHandler MyEvent;

这篇关于为什么BinaryFormatter的尝试序列化的Serializable类的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆