如何忽略二进制序列化的 Event 类成员?

发布于 2024-08-23 19:28:45 字数 555 浏览 6 评论 0原文

我需要避免序列化 Event 类成员,因为当事件由未标记为可序列化的对象处理时,序列化将失败。

我尝试在 Event 类成员上使用 NonSerialized 属性,但无法编译。这行代码:

<NonSerialized()> Public Event PropertyValueChanged()

产生以下错误:

属性“NonSerializedAttribute” 不能应用于 'PropertyValueChanged' 因为 属性对此无效 声明类型。

Public Event PropertyValueChanged() ' compiles but needs the extra handling described below

还有其他方法可以避免序列化事件成员吗?

如果事件未处理,这不是问题,我可以通过在序列化对象之前克隆对象(并忽略事件)来解决这个问题。只是想知道是否有更好的方法。

谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

软糖 2024-08-30 19:28:45

在 C# 中,您可以按如下方式执行此操作,因此我希望这可以在 VB 中实现相同的转换。

请注意,这仅适用于类似字段的事件(即您没有自己的添加/删除):

[field: NonSerialized]
public event EventType EventName;

否则类似:

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

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; }
}
冬天的雪花 2024-08-30 19:28:45

它不起作用,因为编译器实际上为事件生成了一个支持字段。要启用它,只需在属性前添加字段前缀:

[field: NonSerialized]
public event EventHandler PropertyValueChanged;

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;
暗喜 2024-08-30 19:28:45

我过去在项目中的做法是实现 IXmlSerialized 接口并手动控制序列化。我发现这使得序列化基于 GUI 的控件(带有大量事件)变得更加容易。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文