C#编译器验证对象时的空状态静态分析

C# Compiler's null state static analysis when validating objects

我在我的项目中启用了 Nullable 检查,并且在代码的很多地方我检查了输入对象及其属性,如果出现问题则抛出异常。但是,如果一切正常,那么我可以确定输入对象不为空。有没有办法告诉编译器,以某种方式使用 NotNullWhen 属性或类似的东西?我不想在代码中的任何地方禁用可空检查。

void Validate(MyClass1? obj1, MyClass2 obj2)
{
    if (obj1 == null || obj2 == null)
    {
        throw new ArgumentNullException();
    }
}

void DoSomething(MyClass1 obj1, MyClass2 obj2)
{
    // This method requires not-null objects
    ...
}

void Process(MyClass1? obj1, MyClass2 obj2)
{
    Validate(obj1, obj2);
    
    // this produces warning, requires to explicitly check if both objects are not null
    DoSomething(ob1, obj2);
}

您可以使用 System.Diagnostics.CodeAnalysis 命名空间中的 NotNullAttribute

Specifies that an output is not null even if the corresponding type allows it. Specifies that an input argument was not null when the call returns.

void Validate([NotNull] MyClass1? obj1, [NotNull] MyClass2 obj2)
{
    ...
}

此外 this 文章也很有帮助。

我认为[NotNull]而且。 [ItemNotNull] 属性就是您要查找的内容。请参阅文档 here and here

NotNullAttribute

表示标记元素的值永远不能为空。

(示例 )

[NotNull] object Foo() {
  return null; // Warning: Possible 'null' assignment
}