How do I ignore event subscribers when serializing an object?

早过忘川 提交于 2019-12-03 16:13:13

问题


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.


回答1:


You have to include "field:" as part of the [NonSerialized] attribute on the event.

i.e.:

[field: NonSerialized]
public event EventHandler Roar;


来源:https://stackoverflow.com/questions/1173667/how-do-i-ignore-event-subscribers-when-serializing-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!