在C#7中,您可以做
if (int.TryParse("123", out int result))
Console.WriteLine($"Parsed: {result}");
或 - 如果您不使用结果,并且只想检查解析是否成功,请丢弃out值:
if (int.TryParse("123", out _))
Console.WriteLine("Syntax OK");
通常可以正常工作,但是在Visual Studio 2017中,第二个示例,其中 out
参数为空,生成警告
警告AD0001:分析仪'Microsoft.codeanalysis.csharp.diarostics.simplifytypenames.csharpsimplifytytypenamediagnasticanalyzer'''type'System.NullReferenceException'带有消息'对象'type'system.nullreference'toge'system.nullReference'
我可以验证它发生的视觉工作室版本是
Visual Studio Enterprise 2017版本15.1(26403.7(版本
Visual Studio Enterprise 2017版本15.2(26430.4(版本
这是一个错误,还是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(,他们确认这是一个错误。您可以在github dotnet/roslyn看到此处的整个状态。
Pilchie在16小时前评论
我可以在15.2中重复研究,但不能15.3。根据堆栈移至编译器,>我很确定这是骗子。@jcouv?jcouv在16小时前评论
是的,这是一个重复(#17229,也可能是另一个(。 它是在DEV15.3(#17544(中固定的,不幸的是,我们无法将>修复>固定到Dev15.2中。 谢谢 @matt11提出了问题,对不起。
它似乎已经修复了,据我所知,将在下一个更新中可用。但是没有宣布的日期将何时将其包括在内,所以我通过"发送反馈/报告问题"在Visual Studio 2017中提交了问题。
注意:
-
这个问题不仅限于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评论中提到的修复程序。查看以下链接:Visual Studio 2017版本15.3预览。安装后,我再次验证了问题,并可以确认它已修复在那里。
感谢所有参加上面讨论的人!(问题注释(