简体   繁体   English

事件实例字段成员可以为null(假设它没有强制设置为null)吗?

[英]Can an event instance field member be null (assuming it is not forcefully set to null)?

Suppose I have this as a member of a class: 假设我把它作为一个类的成员:

public event EventHandler<MyObject> SomeEventThing;

to avoid a nullable reference warning, I have to write: 为了避免可引用的参考警告,我必须写:

public event EventHandler<MyObject>? SomeEventThing;

Does this mean the event field could be null and I've been playing with fire the entire time? 这是否意味着事件字段可能为空并且我一直在玩火? Or is this an analyzer bug? 或者这是一个分析器错误?

Yes, a field-like event can absolutely be null - and will be if there are no subscribers to the event. 是的,类似字段的事件绝对可以为空 - 并且如果事件没有订阅者将会是空的。 The compiler is correct. 编译器是正确的。 The generated event code is backed by a field of the delegate type, and the default value of the field is still null like other reference type fields. 生成的事件代码由委托类型的字段支持,并且字段的默认值仍然像其他引用类型字段一样为空。

Note that with the null-conditional ?. 请注意,使用null条件?. operator, it's easy to conditionally invoke the event handlers: 运算符,很容易有条件地调用事件处理程序:

SomeEventThing?.Invoke(this, new EventArgs<MyObject>());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM