当使用BinaryFormatter
序列化以下类时,订阅Roar
事件的任何对象也将被序列化,因为对这些对象的引用由EventHandler委托保存。
[Serializable]
public class Lion
{
public event EventHandler Roar;
public string Name { get; set; }
public float Fluffiness { get; set; }
public Lion(string name, float fluffiness)
{
Name = name;
Fluffiness = fluffiness;
}
public void Poke()
{
Roar(); // Could be null, etc..
}
}
如何阻止事件订阅者作为对象图的一部分进行序列化,从Lion开始?
将[NonSerializable]
属性放在event
上将无法编译。
注意:我正在回答我自己的问题,因为我认为在网站上提供信息可能会有用!
常见问题解答:提出并回答您自己的问题也很好,但假装您正在使用Jeopardy:用问题的形式说出来。
答案 0 :(得分:25)
您必须在field:
上添加“[NonSerialized]
”作为event
属性的一部分。
即:
[field: NonSerialized]
public event EventHandler Roar;