不可为空的属性必须包含非空值

Dey*_*Paz 5 .net c# visual-studio asp.net-web-api

有没有办法处理 Visual Studio for mac 中的“非空属性必须包含非空值”警报。好吧,我找不到通过从 csproj 项目文件或配置中删除该行来禁用它的方法。这些警告位于我的数据库模型和视图中,我们的想法是以最佳方式进行。应该说我用的是.Net 6.0

预先感谢您花时间阅读这个问题。

Jef*_*ado 18

我假设您启用了可为空的引用类型。有多种方法可以解决这个问题。

  1. 直接在属性声明中或在构造函数中将这些属性显式初始化为默认值或已知值。
    public class SomeType
    {
        public string SomeProperty { get; set; } = default!;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 禁用整个文件或部分的可为空引用类型。
    #nullable disable // at the top of the file
    
    #nullable restore // after the block of code you wanted to temporarily disable
    
    Run Code Online (Sandbox Code Playgroud)
  3. 禁用整个项目的可为空引用类型。
    删除或更改<Nullable>项目文件中的设置。(在 .NET 6 中默认启用)

我会尝试只坚持#1。如果打算进行过渡,请保留#3。