【发布时间】:2022-02-04 04:55:09
【问题描述】:
我收到警告“退出构造函数时不可为空的事件 'SomeEvent' 必须包含非空值。考虑将事件声明为可空。”
这是我的代码的一个非常简化的版本,它复制了完全相同的问题。我在这里想念什么?这和.Net 6有什么关系吗?
namespace ConsoleApp3
{
public delegate void SomeDelegate(object sender, EventArgs args);
public class NewClass
{
public NewClass(string name)
{
this.name = name;
}
public string name { get; set; }
public event SomeDelegate SomeEvent;
}
}
【问题讨论】:
-
不在我的开发机器附近,但我通常这样声明我的事件:
public event SomeDelegate SomeEvent = delegate { };以防止它为空 -
public event SomeDelegate? SomeEvent;应该修复该警告,使其成为nullable。 -
正如@zaggler 所说,但是当你调用事件时不要忘记像这样使用它
SomeEvent?.Invoke(...); -
这只是因为您为项目启用了可为空的引用类型。
-
@DavidG 是正确的,我认为它也是默认启用的。
标签: c# .net events delegates non-nullable