如果编译它,为什么 C#7 语法中的 TryParse(清空参数)会发出警告?

Why is TryParse in C#7 syntax (empty out parameter) emitting a warning if you compile it?

在 C#7 中,您可以这样做

            if (int.TryParse("123", out int result)) 
                Console.WriteLine($"Parsed: {result}");

或者 - 如果您不使用结果而只是想检查解析是否成功,discard 输出值:

           if (int.TryParse("123", out _))
                Console.WriteLine("Syntax OK");                

这通常工作正常,但在 Visual Studio 2017 第二个示例中,out 参数为空, 生成警告

Warning AD0001: Analyzer 'Microsoft.CodeAnalysis.CSharp.Diagnostics.SimplifyTypeNames.CSharpSimplifyTypeNamesDiagnosticAnalyzer' threw an exception of type 'System.NullReferenceException' with message 'Object reference not set to an instance of an object.'.

我可以验证它发生的Visual Studio版本是

Visual Studio Enterprise 2017 Version 15.1 (26403.7) Release
Visual Studio Enterprise 2017 Version 15.2 (26430.4) Release

这是一个错误,还是 int.TryParse("123", out _) 的用法不受官方支持?到目前为止我找不到任何提示。


为了完整性,这里是显示问题的控制台应用程序代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            if (int.TryParse("123", out _))
                Console.WriteLine("Syntax OK");
        }
    }
}

我向开发团队提交了 错误请求(请求#19180),他们确认这是一个错误。 您可以在此处查看完整状态 at GitHub dotnet/roslyn.

Pilchie commented 16 hours ago
I can repro that in 15.2, but not 15.3. Moving to compiler based on the stack, >Abut I'm pretty sure this is a dupe. @jcouv?

jcouv commented 16 hours ago
Yes, this is a duplicate (of #17229 and possibly another one too). It was fixed in dev15.3 (#17544) and we were unfortunately unable to pull the >fix into dev15.2. Thanks @Matt11 for filing the issue and sorry for the bug.

它似乎已经修复,据我所知,将在下一次更新中提供。但是微软并没有宣布它会被收录的日期,所以我在 Visual Studio 2017 年通过 "Send Feedback/Report a Problem" 提交了一个问题。

备注:

  • 问题不仅限于 TryParse。我验证了如果您编写自己的函数也会发生这种情况,即以下示例也显示警告 AD0001:

    static void Main(string[] args)
    {   
            bool myOutDemo(string str, out int result)
            {
                    result = (str??"").Length;
                    return result > 0;
            }
            // discard out parameter
            if (myOutDemo("123", out _)) Console.WriteLine("String not empty"); 
    }
    
  • 我注意到现在有一​​个 VS 版本 15.3 预览可用,其中应该包含 GitHub 评论中提到的修复。查看以下 link:Visual Studio 2017 Version 15.3 Preview。安装后,我再次验证了这个问题,可以确认它在那里被修复了。


感谢以上参与讨论的各位! (问题评论)