gpt4 book ai didi

c# - 为什么 BinaryFormatter 试图在可序列化类上序列化事件?

转载 作者:可可西里 更新时间:2023-11-01 08:38:25 24 4
gpt4 key购买 nike

我有一个标记为可序列化的简单类,它恰好有一个事件。我试图将事件成员标记为 NonSerialized,但是编译器提示。然而,当我去序列化类实例时,BinaryFormatter 抛出事件不可序列化的异常。这是否意味着您不能序列化具有事件的类?如果是这样,那么编译器应该预先说明。

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);
}

未能完成以下类(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


NonSerializedAttribute 前加上字段

[field:NonSerialized]
public event MyEventHandler MyEvent;

关于c# - 为什么 BinaryFormatter 试图在可序列化类上序列化事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2308620/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com