为什么BinaryFormatter的尝试序列化的Serializable类的事件?事件、序列化、BinaryFormatter、Serializable

由网友(£爷↘继续堕落彡)分享简介:我有一个标记为可序列化一个简单的类,它恰好有一个事件。我试图为事件成员作为非序列化,但是编译器会抱怨。然而,当我去序列化类的实例,该BinaryFormatter的抛出一个异常,该事件是不可序列化。这是否意味着你不能序列化有事件的类?如果是这样,那么编译器应该这么说了前面。流文件= File.open方法(F,File...

我有一个标记为可序列化一个简单的类,它恰好有一个事件。我试图为事件成员作为非序列化,但是编译器会抱怨。然而,当我去序列化类的实例,该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;
 
c BinaryFormatter序列化后的结果是什么

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;

阅读全文

相关推荐

最新文章