我需要避免序列化 Event 类成员,因为当事件由未标记为可序列化的对象处理时,序列化将失败。
我尝试在 Event 类成员上使用 NonSerialized 属性,但编译失败。这行代码:
<NonSerialized()> Public Event PropertyValueChanged()
产生以下错误:
Attribute 'NonSerializedAttribute' cannot be applied to 'PropertyValueChanged' because the attribute is not valid on this declaration type.
Public Event PropertyValueChanged() ' compiles but needs the extra handling described below
还有其他方法可以避免序列化 Event 成员吗?
如果事件未被处理,这不是问题,我可以通过在序列化对象之前克隆对象(并忽略事件)来解决这个问题。只是想知道是否有更好的方法。
谢谢。
最佳答案
在 C# 中,您可以按以下方式执行此操作,所以我希望这与 VB 的翻译相同。
请注意,这仅适用于类似字段的事件(即您没有自己的add
/remove
):
[field: NonSerialized]
public event EventType EventName;
否则类似:
[NonSerialized]
EventType backingField;
public event EventType {
add { backingField += value; }
remove { backingField -= value; }
}
关于c# - 如何忽略二进制序列化的事件类成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2389381/