2011-05-20 51 views

回答

93

你最終還是要決定什麼空測試特定的值布爾將代表。如果null應該是false,你可以這樣做:

bool newBool = x.HasValue ? x.Value : false; 

或者:

bool newBool = x.HasValue && x.Value; 

或者:

bool newBool = x ?? false; 
+0

如果你這樣做,在'VB.NET'中怎麼樣:'dim newBool​​ as Boolean = CBool​​(x)'? 將'null'轉換爲'false'還是會引發異常? – 2017-03-08 14:37:45

+0

這是否甚至編譯? – 2017-03-08 20:12:07

+0

是的 - 它在'快速行動'中爲'Linq'聲明'Where'子句提出,我不明白爲什麼'提升運算符'似乎在Linq內部不起作用(也許它只是VB.NET ?) - 我剛剛測試過,它確實會拋出無效的投射異常 – 2017-03-09 09:38:05

84

可以使用null-coalescing operatorx ?? something,其中something是要使用,如果xnull一個布爾值。

實施例:

bool? myBool = null; 
bool newBool = myBool ?? false; 

newBool將是假的。

+1

那麼,布爾? myBool = null; bool newBool​​ = myBool ?? false;' – CaffGeek 2011-05-20 17:54:19

2

喜歡的東西:

if (bn.HasValue) 
{ 
    b = bn.Value 
} 
2

完整的方法是:

bool b1; 
bool? b2 = ???; 
if (b2.HasValue) 
    b1 = b2.Value; 

,也可以使用

bool b3 = (b2 == true); // b2 is true, not false or null 
4

最簡單的方法是使用空合併運算符:??

bool? x = ...; 
if (x ?? true) { 

} 

具有可空值的??通過檢查提供的可空表達式工作。如果空的表達式有它的價值會被其他人使用的值,它將使用上的??

2
bool? a = null; 
bool b = Convert.toBoolean(a); 
61

右邊的表達式可以使用Nullable{T}GetValueOrDefault()方法。如果爲null,這將返回false。

bool? nullableBool = null; 

bool actualBool = nullableBool.GetValueOrDefault(); 
+4

我認爲這是簡潔性和C#noob-friendlyliness之間最好的混合體。還請注意,您可以指定默認值的地方有超載。 – Phil 2011-05-20 18:10:40

+1

我喜歡使用這種方法,因爲它可以創建'優雅'if語句if(nullableBool.GetValueOrDefault())' – 2014-08-26 07:48:02

3

如果你打算在if語句中使用的bool?,我找到最簡單的辦法是比較反對任何truefalse

bool? b = ...; 

if (b == true) { Debug.WriteLine("true"; } 
if (b == false) { Debug.WriteLine("false"; } 
if (b != true) { Debug.WriteLine("false or null"; } 
if (b != false) { Debug.WriteLine("true or null"; } 

當然,您也可以與null進行比較。

bool? b = ...; 

if (b == null) { Debug.WriteLine("null"; } 
if (b != null) { Debug.WriteLine("true or false"; } 
if (b.HasValue) { Debug.WriteLine("true or false"; } 
//HasValue and != null will ALWAYS return the same value, so use whatever you like. 

如果你打算將它轉換成一個布爾傳授給應用程序的其他部分,則空聯合運營是你想要的。

bool? b = ...; 
bool b2 = b ?? true; // null becomes true 
b2 = b ?? false; // null becomes false 

如果您已經檢查了空,只是想和你的價值,然後訪問Value屬性。

bool? b = ...; 
if(b == null) 
    throw new ArgumentNullException(); 
else 
    SomeFunc(b.Value); 
0

這是對主題的有趣變化。在第一眼和第二眼中,你會假設真正的分支被採取。並非如此!

bool? flag = null; 
if (!flag ?? true) 
{ 
    // false branch 
} 
else 
{ 
    // true branch 
} 

的方式得到你想要的是要做到這一點:

if (!(flag ?? true)) 
{ 
    // false branch 
} 
else 
{ 
    // true branch 
} 
1

這個答案是對使用情況下,當你只是想在一個條件來測試bool?。它也可以用來獲得正常的bool。這是一個替代我personnaly發現比coalescing operator ??更容易閱讀。

如果你想測試一個條件,你可以使用這個

bool? nullableBool = someFunction(); 
if(nullableBool == true) 
{ 
    //Do stuff 
} 

以上,如果爲真只有當bool?是真實的。

你也可以用它來從bool?

bool? nullableBool = someFunction(); 
bool regularBool = nullableBool == true; 

巫分配規則bool相同

bool? nullableBool = someFunction(); 
bool regularBool = nullableBool ?? false;