【问题标题】:How do I ignore event subscribers when serializing an object?序列化对象时如何忽略事件订阅者?
【发布时间】:2009-07-23 18:34:09
【问题描述】:

当使用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 上将无法编译。


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

常见问题解答:提出并回答您自己的问题也很好,但假装您处于危险境地:以问题的形式表达。

【问题讨论】:

    标签: c# .net events serialization binaryformatter


    【解决方案1】:

    您必须在event[NonSerialized] 属性中包含“field:”。

    即:

    [field: NonSerialized]
    public event EventHandler Roar;
    

    【讨论】:

    • 谢谢。但这是为什么呢?
    • 是因为 System.NonSerializedAttribute 有一个约束:只能应用于字段!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 2014-05-11
    • 1970-01-01
    • 2016-01-22
    • 2016-11-21
    • 1970-01-01
    相关资源
    最近更新 更多