检查OpenFileDialog.OpenFile是否为null

时间:2015-02-16 12:25:02

标签: c# null

我已经在the msdn doc中了解了这段代码:

Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
[...] // Some init
try
{
    if ((myStream = openFileDialog1.OpenFile()) != null)
    {
        using (myStream)
        {
            // Insert code to read the stream here.
        }
    }
}

但Resharper温和地告诉我,检查null是没用的:

enter image description here

我应该信任Resharper还是Microsoft?

1 个答案:

答案 0 :(得分:2)

R#是正确的,如果您反编译该类(请参阅下面的代码),它的实现方式永远不会返回null (它总是返回一个流或抛出例外):

public Stream OpenFile()
{
    IntSecurity.FileDialogOpenFile.Demand();
    string str = this.FileNamesInternal[0];

    if (str == null || str.Length == 0)
        throw new ArgumentNullException("FileName");

    new FileIOPermission(FileIOPermissionAccess.Read, IntSecurity.UnsafeGetFullPath(str)).Assert();

    try
    {
        return (Stream) new FileStream(str, FileMode.Open, FileAccess.Read, FileShare.Read);
    }
    finally
    {
        CodeAccessPermission.RevertAssert();
    }
}

那说:

  • 添加空检查在该特定用例中根本不会改变性能,因此您可以保留它。作为一般规则,在使用之前检查不属于您的函数的结果为null并不是一种不好的做法
  • 就像每个软件一样,R#有时会出现错误(例如:Why does ReSharper think that "thread.Name == null" is always false?),所以不要盲目遵循它的所有建议:)
  • MSDN示例有时写得不好,或者更糟糕,所以不要盲目地复制/粘贴所有示例:)