启用Nullable布尔值:当值为true时,case转到null
我意识到处理可空类型的正确方法是使用HasValue属性。 但我想知道为什么以下switch语句在null case而不是default上打破。 使用VS2015 C#4.0。 另一台使用VS2010 C#4.0的计算机没有同样的问题。
private void Testing() { bool? boolValue = true; switch (boolValue) { case null: break; //even though value is true, code runs here default: break; } }
编辑 :如果仅指定case Null
和default
则使用任何Nullable
观察行为。
这将是一个非常简短的答案:你刚刚在两周前报道了Roslyn bug#4701 。
里程碑设置为1.1,因此您现在必须使用单独的if
子句解决此问题,同时等待下一次编译器更新。
这不是答案,我只是分享由VS2013和VS2015生成的IL代码。
原始C#代码:
public void Testing() { bool? boolValue = true; switch (boolValue) { case null: Console.WriteLine("null"); break; default: Console.WriteLine("default"); break; } }
VS2013 IL(反编译):
public void Testing() { bool? boolValue = new bool?(true); bool valueOrDefault = boolValue.GetValueOrDefault(); if (boolValue.HasValue) { Console.WriteLine("default"); } else { Console.WriteLine("null"); } }
VS2015 IL(反编译):
public void Testing() { bool? flag = new bool?(true); bool? flag2 = flag; bool? flag3 = flag2; if (flag3.HasValue) { bool valueOrDefault = flag3.GetValueOrDefault(); } Console.WriteLine("null"); }