【问题标题】:"Non-nullable event must contain a non-null value when exiting constructor"“退出构造函数时不可为空的事件必须包含非空值”
【发布时间】: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


【解决方案1】:

我知道我参加聚会迟到了,但 Google 把我发到这里,唯一的答复是不满意。 I came upon another answer on StackOverflow 感觉好多了,你可以在那里得到很好的解释。

tl;dr 只是让事件可以为空,因为它实际上是这样的:

public event SomeDelegate? SomeEvent;  

【讨论】:

    猜你喜欢
    • 2021-08-02
    • 2022-10-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 2012-11-26
    • 1970-01-01
    • 2017-11-15
    • 1970-01-01
    相关资源
    最近更新 更多