.net – 当我检查空值时禁用空引用警告

前端之家收集整理的这篇文章主要介绍了.net – 当我检查空值时禁用空引用警告前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在下面的代码中,如果cmd已经初始化,那么我将确保在抛出异常之前关闭所有打开的连接.但是,即使在我检查cmd不为null之后,我仍然在后续代码行中得到可能的空引用警告.

Dim cmd As sqlCommand
Try
    'Do some Stuff
Catch ex As Exception
    If cmd IsNot Nothing AndAlso
       cmd.Connection IsNot Nothing AndAlso              '<- null cmd warning 
       cmd.Connection.State = ConnectionState.Open Then  '<- null cmd warning 
        cmd.Connection.Close()                           '<- null cmd warning 
    End If
    Throw
End Try

我得到以下两个警告(可能是来自Resharper和来自Visual Studio的一个):

  • Variable ‘x’ might not be initialized before accessing. A null reference exception could occur at runtime.
  • BC42104: Variable ‘x’ is used before it has been assigned a value. A null reference exception could result at runtime.

根据Visual Studio Page

An application has at least one possible path through its code that reads a variable before any value is assigned to it.

但我认为甚至没有一条可能的路径通过代码,在没有初始化的情况下使用变量.

>我犯了一些错误或者这是一个错误吗?
>有没有办法禁用此警告?

这是一个截图:

这与此处已经提到的许多类似问题不同,例如Prevent Resharper “Possible Null Reference Exception” warnings,因为我不是试图允许NullableType,而是已经保证我的变量不为null.

更新:

跟进问题:为什么?

无论我的对象是从未初始化还是初始化为Nothing,在两种情况下cmd IsNot Nothing都不应解析为False,因此AndAso之后的任何内容都不应该被执行.

Dim cmd1 As sqlCommand
Console.Write(cmd1 IsNot Nothing) 'False

Dim cmd2 As sqlCommand = Nothing
Console.Write(cmd2 IsNot Nothing) 'False

也许编译器在编译时没有很好的方法来保证这一点.

解决方法

您的问题不是您的值为null,问题是您的对象根本没有初始化.例如:

static void Main(string[] args)
    {
        List<int> empty;

        if (empty != null)
        {
            Console.WriteLine("no");
        }
    }

不会编译,因为空没有价值.如果我将代码更改为:

static void Main(string[] args)
    {
        List<int> empty = null;

        if (empty != null)
        {
            Console.WriteLine("no");
        }
    }

它会工作,因为我的列表现在有一个值,它是null,但它仍然存在.

编辑:对不起我使用C#而不是VB,这是因为我编写的编辑器很方便,但代码是正确的.你每次都初始化你的变量,你不会得到错误.

猜你在找的VB相关文章