【发布时间】:2013-04-24 16:36:12
【问题描述】:
以下代码导致使用未分配的局部变量“numberOfGroups”:
int numberOfGroups;
if(options.NumberOfGroups == null || !int.TryParse(options.NumberOfGroups, out numberOfGroups))
{
numberOfGroups = 10;
}
但是,这段代码可以正常工作(尽管ReSharper 说= 10 是多余的):
int numberOfGroups = 10;
if(options.NumberOfGroups == null || !int.TryParse(options.NumberOfGroups, out numberOfGroups))
{
numberOfGroups = 10;
}
是我遗漏了什么,还是编译器不喜欢我的||?
我已将其缩小到导致问题的dynamic(options 是我上面代码中的一个动态变量)。问题仍然存在,为什么我不能这样做?
这段代码不能编译:
internal class Program
{
#region Static Methods
private static void Main(string[] args)
{
dynamic myString = args[0];
int myInt;
if(myString == null || !int.TryParse(myString, out myInt))
{
myInt = 10;
}
Console.WriteLine(myInt);
}
#endregion
}
但是,这段代码确实:
internal class Program
{
#region Static Methods
private static void Main(string[] args)
{
var myString = args[0]; // var would be string
int myInt;
if(myString == null || !int.TryParse(myString, out myInt))
{
myInt = 10;
}
Console.WriteLine(myInt);
}
#endregion
}
我没有意识到 dynamic 会是其中的一个因素。
【问题讨论】:
-
不要认为知道你没有使用传递给
out参数的值作为输入足够聪明 -
这里给出的代码没有展示所描述的行为;它工作得很好。请发布实际演示您所描述的行为我们可以自己编译的代码。给我们整个文件。
-
啊,现在我们有了一些有趣的东西!
-
编译器对此感到困惑并不奇怪。动态调用站点的帮助程序代码可能有一些不能保证分配给
out参数的控制流。考虑编译器应该生成什么帮助代码来避免这个问题,或者这是否可能,这当然很有趣。 -
乍一看,这确实像一个错误。
标签: c# c#-4.0 dynamic compiler-construction cil