從 bool? 安全地強制轉換爲 bool ??應用

bool? 能夠爲 null 的類型能夠包含三個不一樣的值:truefalse 和 null。所以,bool? 類型不能用於條件語句,如 iffor 或 while。例如,此代碼沒法編譯,並將報告編譯器錯誤 CS0266安全

 
 
bool? b = null;
if (b) // Error CS0266.
{
}

這是不容許的,由於 null 在條件上下文中的含義並不清楚。若要在條件語句中使用 bool?,請首先檢查其 HasValue 屬性以確保其值不是 null,而後將它強制轉換爲 bool。有關更多信息,請參見 bool。若是對使用 null 值的 bool? 執行強制轉換,則在條件測試中將引起InvalidOperationException。下面的示例演示了一種從 bool? 安全地強制轉換爲 bool 的方法:測試

示例
 
 
 
            bool? test = null;
             ...// Other code that may or may not
                // give a value to test.
            if(!test.HasValue) //check for a value
            {
                // Assume that IsInitialized
                // returns either true or false.
                test = IsInitialized();
            }
            if((bool)test) //now this cast is safe
            {
               // Do something.
            }


public bool? c = null;
public bool T()
{this

return c ?? false;spa

} 解釋code

若是 ?? 運算符的左操做數非 null,該運算符將返回左操做數,不然返回右操做數。
 p ?? false
相關文章
相關標籤/搜索