代码之家  ›  专栏  ›  技术社区  ›  CB_at_Sw

Visual Studio 2022警告“此处“xxx”可能为null”,即使“xxx”不可能为null

  •  1
  • CB_at_Sw  · 技术社区  · 2 年前

    我有一个类似的C#方法(net6.0):

    bool TryDoSomething(out MyObject1? obj1, out MyObject2? obj2)
    {
        obj1 = DoSomethingElse();
        obj2 = DoAnotherThing();
       
        //Do some other things....
        
        return obj1 != null && obj2 != null;
    }
    

    这是通过另一种方法调用的:

    bool CallingMethod()
    {
        if (!TryDoSomething(out var obj1, out var obj2))
            return false;
    
        obj1.PerformSomeAction();
        obj2.PerformADifferentAction();
        
        //Do many other things....
        
        return true;
    
    }
    

    从的定义可以清楚地看出 TryDoSomething() 以及我提前离开的事实 return false ,不可能 obj1 obj2 可能是 null 到…的时候 obj1.PerformSomeAction() obj2.PerformADifferentAction() 被调用(由于 TryDoSomething() 返回 false 在到达那些线之前)。

    然而,尽管如此,Visual Studio在 obj1 obj2 通知我 'xxx' may be null here 。。。。。 Dereference of a possibly null reference 。(其中“xxx”是“obj1”或“obj2”)。

    这怎么会发生?这是Visual Studio本身的错误吗?

    1 回复  |  直到 2 年前
        1
  •  1
  •   Jeppe Stig Nielsen    2 年前

    必须声明具有属性的第一个方法:

    bool TryDoSomething([NotNullWhen(true)] out MyObject1? obj1, [NotNullWhen(true)] out MyObject2? obj2)
    {
    ...
    }
    

    在你的内部 CallingMethod() ,分析不试图理解的内部工作原理 另外 方法 TryDoSomething(...) 因此,如果返回值和参数的null状态之间存在某种联系,则必须与属性进行通信。

    阅读 Attributes for null-state static analysis interpreted by the C# compiler 以了解更多信息。

    推荐文章