可以阻止 CS8602(变量可能为 null)作为包所有者

It's possible to prevent CS8602 (variable may be null) as the package owner

提问人:Muflix 提问时间:10/10/2022 更新时间:10/10/2022 访问量:565

问:

例如,我有 xUnit 测试

var record = _context.Records.Where(x => x.Foo == FooValue).FirstOrDefault();

// This check WILL NOT prevent the warning from being displayed
Assert.NotNull(record);

// This check WILL prevent the warning from being displayed
if (record == null) throw new Exception(); 

// Warning CS8602 "record may be null here"
Assert.True(record.Foo == FooValue); 

包的所有者(通常)可以以某种方式指示编译器该方法的输出符合警告 CS8602?我使用了几个包,但我看到不相关的警告,我不想放置

#pragma warning disable CS8602 // Dereference of a possibly null reference.
#pragma warning restore CS8602 // Dereference of a possibly null reference.

到处。如果可能的话,我至少会在我拥有的软件包中解决这个问题。

C# visual-studio nullreferenceexception 编译器警告

评论

2赞 Amir 10/10/2022
使用此 Assert.True(record!.Foo == FooValue);
0赞 Matthew Watson 10/10/2022
你为什么不在那个例子中使用?_context.Records.Where(x => x.Foo == FooValue).First();
1赞 Hans Kesting 10/10/2022
您可以添加多个属性
1赞 Muflix 10/10/2022
@Amir 我不知道空原谅操作员谢谢!
1赞 Matthew Watson 10/10/2022
如果要断言从正在实现的方法返回的值,并且正在启用 Nulllable,只需确保不要在方法声明的末尾放置 a。?

答:

4赞 Curllog 10/10/2022 #1

要解决可为 null 的警告,您可以使用 !在 C 中#

检查此页: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/nullable-warnings

例如: Assert.True(记录。呜呜!== FooValue);