为什么这个(null ||!TryParse)条件导致“使用未分配的局部变量”? [英] Why does this (null || !TryParse) conditional result in "use of unassigned local variable"?
问题描述
以下代码导致使用未分配的本地变量numberOfGroups:
The following code results in use of unassigned local variable "numberOfGroups":
int numberOfGroups;
if(options.NumberOfGroups == null || !int.TryParse(options.NumberOfGroups, out numberOfGroups))
{
numberOfGroups = 10;
}
但是,这段代码工作正常(虽然, ReSharper 说 = 10
是多余的):
However, this code works fine (though, ReSharper says the = 10
is redundant):
int numberOfGroups = 10;
if(options.NumberOfGroups == null || !int.TryParse(options.NumberOfGroups, out numberOfGroups))
{
numberOfGroups = 10;
}
我错过了一些东西,或者编译器不喜欢我的 ||
?
Am I missing something, or is the compiler not liking my ||
?
我把这个缩小到动态
在上面的代码中,问题(选项
是一个动态变量)。问题仍然存在,为什么我不能这样做?
I've narrowed this down to dynamic
causing the issues (options
was a dynamic variable in my above code). The question still remains, why can't I do this?
此代码不编译: / p>
This code doesn't compile:
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
}
没有意识到动态
将成为这个因素。
I didn't realize dynamic
would be a factor in this.
推荐答案
我很确定这是一个编译器错误。很好找!
I am pretty sure this is a compiler bug. Nice find!
编辑:它不是一个bug,正如Quartermeister所示;动态可能会执行一个奇怪的 true
运算符,这可能导致 y
永远不会被初始化。
it is not a bug, as Quartermeister demonstrates; dynamic might implement a weird true
operator which might cause y
to never be initialized.
这是一个最小的复制:
class Program
{
static bool M(out int x)
{
x = 123;
return true;
}
static int N(dynamic d)
{
int y;
if(d || M(out y))
y = 10;
return y;
}
}
我没有理由认为这是非法的;如果你用bool替换动态,那么它编译得很好。
I see no reason why that should be illegal; if you replace dynamic with bool it compiles just fine.
我实际上明天和C#团队见面;我会把它提到他们对错误抱歉!
I'm actually meeting with the C# team tomorrow; I'll mention it to them. Apologies for the error!
这篇关于为什么这个(null ||!TryParse)条件导致“使用未分配的局部变量”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!