How to ignore Event class member for binary serialization?

五迷三道 提交于 2019-12-20 11:52:29

问题


I need to avoid serializing an Event class member because when the event is handled by an object that is not marked as Serializable the serialization will fail.

I tried using the NonSerialized attribute on the Event class member but it fails to compile. This line of code:

<NonSerialized()> Public Event PropertyValueChanged()

produces the following error:

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

Is there another way to avoid serializing Event members?

This is not a problem if the event is not handled and I can work around it by cloning the objects (and ignoring the event) before serializing them. Just wondering if there is a better way.

Thanks.


回答1:


In C# you can do this as below, so I hope this translates identically to VB.

Note this only applies to field-like events (i.e. where you don't have your own add/remove):

[field: NonSerialized]
public event EventType EventName;

Otherwise something like:

[NonSerialized]
EventType backingField;
public event EventType {
    add { backingField += value; }
    remove { backingField -= value; }
}



回答2:


It isn't working because the compiler actually generates a backing field for the event. To enable it, just prefix your attribute with field:

[field: NonSerialized]
public event EventHandler PropertyValueChanged;



回答3:


How I've done it in the past for projects is implement the IXmlSerializable interface and control my serialization manually. I find this makes serializing GUI based controls (with lots of events) much easier.

IXmlSerializable



来源:https://stackoverflow.com/questions/2389381/how-to-ignore-event-class-member-for-binary-serialization

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