Pau*_*sik 16 .net c# vb.net events binary-serialization
我需要避免序列化Event类成员,因为当事件由未标记为Serializable的对象处理时,序列化将失败.
我尝试在Event类成员上使用NonSerialized属性,但无法编译.这行代码:
<NonSerialized()> Public Event PropertyValueChanged()
Run Code Online (Sandbox Code Playgroud)
产生以下错误:
属性'NonSerializedAttribute'不能应用于'PropertyValueChanged',因为该属性在此声明类型上无效.
Public Event PropertyValueChanged() ' compiles but needs the extra handling described below
Run Code Online (Sandbox Code Playgroud)
有没有其他方法可以避免序列化活动成员?
如果事件未被处理,这不是问题,我可以通过在序列化之前克隆对象(并忽略事件)来解决它.只是想知道是否有更好的方法.
谢谢.
Mar*_*ell 34
在C#中你可以这样做,所以我希望这与VB相同.
请注意,这仅适用于现场般的事件(即,你没有自己add
/ remove
):
[field: NonSerialized]
public event EventType EventName;
Run Code Online (Sandbox Code Playgroud)
否则之类的:
[NonSerialized]
EventType backingField;
public event EventType {
add { backingField += value; }
remove { backingField -= value; }
}
Run Code Online (Sandbox Code Playgroud)
它不起作用,因为编译器实际上为事件生成了一个支持字段.要启用它,只需在属性前添加字段:
[field: NonSerialized]
public event EventHandler PropertyValueChanged;
Run Code Online (Sandbox Code Playgroud)