当将SqlCommand.ExecuteReader()返回null?SqlCommand、ExecuteReader、null

2023-09-03 04:48:31 作者:夜店、情殇

在使用调用 SqlCommand.ExecuteReader()方法,ReSharper的告诉我,我有可能NullReference例外,当我使用SqlDataReader对象之后。

When using calling the SqlCommand.ExecuteReader() method, ReSharper tells me I have a possible NullReference exception when I use the SqlDataReader object afterwards.

因此​​,与下面的code:

So with the following code:

using (SqlConnection connection = GetConnection())
{
    using (SqlCommand cmd = connection.CreateCommand())
    {
        cmd.CommandText = ; //snip

        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                //snip
            }
        }
    }
}

而(reader.Read())行带有下划线。

我的问题是,当将读者对象永远是空?我从来没有遇到过的文档中并没有提到它可以。我应该检查它是否为空或者是安全的忽略?

My question is when would the reader object ever be null? I've never come across it and the documentation doesn't mention that it could be. Should I be checking if it's null or is it safe to ignore?

和为什么ReSharper的认为,这可能是为空,例如当它让我使用SqlCommand不推荐它来检查空?我想有上ExecuteReader方法的属性。

And why would ReSharper think that it could be null, when for example it lets me use the SqlCommand without recommending it be checked for null? I'm guess there's an attribute on the ExecuteReader method.

推荐答案

这是一个误报。

反思SqlDataReader.ExecuteReader,我可以看到读者返回空值的唯一方法是,如果内部RunExecuteReader方法传递假的returnStream,它不是。

Reflecting on SqlDataReader.ExecuteReader, I can see that the only way the reader is returned as null is if the internal RunExecuteReader method is passed 'false' for returnStream, which it isn't.

在SqlDataReader的深处, A 阅读器的构造函数总是被调用在某些时候,所以我pretty的肯定,这是不是身体可能的ExecuteReader返回空值。

In the depths of SqlDataReader, a reader constructor is always called at some point, so I'm pretty sure this is not physically possible for ExecuteReader to return null.