簡體   English   中英

轉換可空的布爾?布爾

[英]Convert nullable bool? to bool

你怎么轉換可空的bool? bool C#中?

我試過x.Valuex.HasValue ......

你最終必須決定null bool代表什么。 如果null應為false ,則可以執行以下操作:

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

要么:

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

要么:

bool newBool = x ?? false;

您可以使用null-coalescing運算符x ?? something x ?? something ,其中something是你想要使用的布爾值,如果xnull

例:

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

newBool將是假的。

您可以使用Nullable{T} GetValueOrDefault()方法。 如果為null,則返回false。

 bool? nullableBool = null;

 bool actualBool = nullableBool.GetValueOrDefault();

最簡單的方法是使用null合並運算符: ??

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

}

?? 可空值的工作原理是檢查提供的可為空的表達式。 如果為空的表達式的值它的價值會被他人用來將使用權的表達??

如果你要使用bool? if語句中,我發現最簡單的方法是比較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以傳遞給應用程序的其他部分,那么Null Coalesce運算符就是您想要的。

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

如果您已經檢查了null,並且只想要該值,則訪問Value屬性。

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

這個答案適用於你只是想測試bool?的用例bool? 在一個條件。 它也可以用於獲得正常的bool 這是一個替代我個人發現比coalescing operator ??更容易閱讀coalescing operator ??

如果要測試條件,可以使用它

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

以上如果只是bool?會是真的bool? 是真的。

您也可以使用這個分配規則的boolbool?

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

女巫是一樣的

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

就像是:

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

完整的方式是:

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

或者您可以使用測試特定值

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

這是主題的有趣變化。 在第一眼和第二眼,你會假設真正的分支被采取。 不是這樣!

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

得到你想要的方法是這樣做:

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

System.Convert對我很好。

using System; ... Bool fixed = Convert.ToBoolean(NullableBool);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM