HOW TO:從 bool? 安全轉型至 bool (C# 程式設計手冊)

更新:2007 年 11 月

可為 null 的型別 bool? 包含三個不同的值:true、false 和 null。因此,bool? 型別無法在某些條件中使用,例如搭配 if、for 或 while 使用。例如,這個程式碼無法編譯,並會出現編譯器錯誤 CS0266

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

因為在條件內容中 null 表示的意義不明確,所以不允許這項動作。若要在條件陳述式中使用 bool?,請先檢查其 HasValue 屬性,確定其值不是 null,然後將它轉型為 bool。如需詳細資訊,請參閱 bool。如果在 bool? 上以 null 值執行轉型,則會在條件測試中擲回 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.
            }

請參閱

概念

C# 程式設計手冊

參考

常值關鍵字 (C# 參考)

可為 Null 的型別 (C# 程式設計手冊)