问题描述
以下代码导致使用未分配的局部变量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 ||?
我已将其缩小到导致问题的 dynamic (options 是我上面代码中的动态变量).问题仍然存在,为什么我不能这样做?
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?
这段代码不能编译:
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 会是其中的一个因素.
I didn't realize dynamic would be a factor in this.
推荐答案
我很确定这是一个编译器错误.很好的发现!
I am pretty sure this is a compiler bug. Nice find!
这不是错误,正如 Quartermeister 所展示的那样;dynamic 可能会实现一个奇怪的 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 替换 dynamic 它编译就好了.
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) 条件会导致“使用未分配的局部变量"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)