![](/img/trans.png)
[英]Pass nullable boolean to partial view not working when value is null
[英]Switch on Nullable Boolean : case goes to null when value is true
我意識到處理可為空類型的正確方法是使用 HasValue 屬性。 但我想知道為什么下面的 switch 語句在 null 情況下而不是默認情況下中斷。 使用 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 錯誤 #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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.