如何:從 bool? 安全地強制轉換為 bool(C# 編程指南)

來源:互聯網
上載者:User

標籤:style   http   color   io   os   使用   ar   for   div   

bool? 可為 Null 的型別可以包含三個不同的值:true、false 和 null。因此,bool? 類型不能用於條件陳述式,如 if、for 或 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.            }

來自

如何:從 bool? 安全地強制轉換為 bool(C# 編程指南)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.