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

查看:104
本文介绍了“使用未分配的局部变量”;在带有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的错误。因此,我想知道为什么编译器对待 string dynamic.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 以获得一份报告

[剪裁示例]


由于这种可能性,如果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天全站免登陆