在序列化对象时如何忽略事件订阅者?

xyz*_*xyz 14 .net c# events serialization binaryformatter

当使用a序列化以下类时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..
    }
}
Run Code Online (Sandbox Code Playgroud)

从Lion开始,您如何阻止事件订阅者被序列化为对象图的一部分?

[NonSerializable]属性放在event将不会编译.


注意:我正在回答我自己的问题,因为我认为在网站上获取信息可能会有用!

常见问题解答:提问和回答你自己的问题也很好,但假装你正在使用Jeopardy:用问题的形式说出来.

xyz*_*xyz 25

你必须包含" field:"作为[NonSerialized]属性的一部分event.

即:

[field: NonSerialized]
public event EventHandler Roar;
Run Code Online (Sandbox Code Playgroud)