序列化对象时如何忽略事件订阅者? [英] How do I ignore event subscribers when serializing an object?
问题描述
当使用 BinaryFormatter
序列化以下类时,任何订阅 Roar
事件的对象也将被序列化因为对这些对象的引用由EventHandler代理持有。
[Serializable]
public class Lion
{
公共事件EventHandler咆哮;
public string Name {get;组; }
public float Fluffiness {get;组;
public Lion(string name,float fluffiness)
{
Name = name;
蓬松度=蓬松;
}
public void Poke()
{
Roar(); //可以是null等等。
}
}
如何将活动订阅者作为对象图的一部分从Lion开始停止?
将 [NonSerializable]
属性事件
将无法编译。
$ b $注意:我正在回答自己的问题,因为我认为在网站上获取信息可能是有用的!
常见问题:请问和回答自己的问题也是完全正确的,但是假装你使用Jeopardy:以问题的形式进行短语。
您必须在 [NonSerialized]
字段:
code>事件的code>属性。 ie:
[field:NonSerialized]
public event EventHandler Roar;
When the following class is serialized with a BinaryFormatter
, any objects subscribing to the Roar
event will also be serialized, since references to those objects are held by the EventHandler delegate.
[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..
}
}
How would you stop event subscribers being serialized as part of the object graph starting with a Lion?
Putting the [NonSerializable]
attribute on the event
will not compile.
Note: I'm answering my own question since I think it might be useful to have the information on the site!
FAQ: It's also perfectly fine to ask and answer your own question, but pretend you're on Jeopardy: phrase it in the form of a question.
You have to include "field:
" as part of the [NonSerialized]
attribute on the event
.
i.e.:
[field: NonSerialized]
public event EventHandler Roar;
这篇关于序列化对象时如何忽略事件订阅者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!