“未分配局部变量的使用"在带有 TryParse 的 if 语句中使用动态 [英] "Use of unassigned local variable" in if statement with TryParse with the use of dynamic

查看:21
本文介绍了“未分配局部变量的使用"在带有 TryParse 的 if 语句中使用动态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在 VS2015 .Net v4.5.2 控制台应用程序中输入了以下代码:

I've just typed in the following code to a VS2015 .Net v4.5.2 console application:

dynamic fromString = "blah", toString = "blah2";
DateTime fromDate, toDate;
if (DateTime.TryParse(fromString.ToString(), out fromDate) && DateTime.TryParse(toString.ToString(), out toDate)) {
    Console.WriteLine(fromDate);
    Console.WriteLine(toDate); 
}

有点出乎意料,我收到错误使用未分配的局部变量 toDate".我没想到会这样,因为只有在从第二个 TryParse 中为 'toDate' 分配了一个值时,才会输入 if 语句.

Somewhat unexpectedly I'm getting the error "Use of unassigned local variable toDate". I didn't expected it because the if statement is only entered if 'toDate' is assigned a value from the second TryParse.

不用说,它可以通过为 'toDate' 分配一个值来解决:

Needless to say, it can be worked around by assigning 'toDate' a value:

DateTime fromDate, toDate = DateTime.MinValue;

或更改 &&到 &这样无论第一个失败,都会执行两个 TryParses.

or changing the && to & so that both TryParses are executed regardless of the first failing.

但是,我想知道为什么会出现错误?如果变量 fromString 和 toString 是字符串,则不会发生错误并且编译器不会给出 toDate 未分配的错误.因此我想知道为什么编译器对 stringdynamic.ToString() 的处理方式不同?

However, I wonder why the error occurs? If the variables fromString and toString were strings, the error does not occur and the compiler does not give the error that toDate is unassigned. Therefore I wonder why the compiler treats string and dynamic.ToString() differently?

推荐答案

这是 Roslyn 的一个重大变化,记录在 此处:

This was a breaking change in Roslyn, documented here:

以前的编译器为动态表达式实现的明确赋值规则允许某些可能导致读取未明确赋值的变量的代码情况.有关一份报告,请参阅 https://github.com/dotnet/roslyn/issues/4509

The definite assignment rules implemented by previous compilers for dynamic expressions allowed some cases of code that could result in variables being read that are not definitely assigned. See https://github.com/dotnet/roslyn/issues/4509 for one report of this.

[截图示例]

由于这种可能性,如果 val 没有初始值,则编译器必须不允许编译此程序.即使 val 没有初始值,以前版本的编译器(VS2015 之前的版本)也允许编译此程序.Roslyn 现在可以诊断此尝试读取可能未初始化的变量.

Because of this possibility the compiler must not allow this program to be compiled if val has no initial value. Previous versions of the compiler (prior to VS2015) allowed this program to compile even if val has no initial value. Roslyn now diagnoses this attempt to read a possibly uninitialized variable.

这篇关于“未分配局部变量的使用"在带有 TryParse 的 if 语句中使用动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆