C# 6.0:Null – Conditional 操作符

來源:互聯網
上載者:User

標籤:style   blog   http   ar   io   color   os   使用   sp   

在引入nameof操作符的同時,C# 6.0 還引入了Null-Conditional操作符。它使開發人員可以檢查object引用鏈中的null值。這個null-conditional 操作符寫作"?.",會在引用鏈中任一個為null時返回null。這避免了對每一級進行null檢查。

假設我們有一個class為Student,它有一個屬性Address,同時這個屬性的type是一個名為Address的Class。現在我們用下面的代碼塊來print它的HomeAddress。

if (student != null && student.Address != null){    WriteLine(student.Address.HomeAddress);}else{    WriteLine("No Home Address");}
View Code

我們可以看到,為了避免null-reference exception,我們不得不檢查student是否為null,然後檢查student.Address是否為null。

現在,上面的代碼會通過使用null-conditional(?.)操作符來重寫成:

WriteLine(student?.Address?.HomeAddress ?? "No Home Address");

是不是很帥?不必分別檢查每個對象,使用“?.”我們可以同時檢查整個引用鏈。任意一級為null,它都會返回null。下面的圖片解釋了“?.”是怎麼工作的。

它也可以和方法協同工作,特別是當我們trigger event的時候。比如下面的代碼

if (AddressChanged != null){    AddressChanged (this, EventArgs.Empty);}
View Code

使用?.我們可以這樣寫。

AddressChanged ?.Invoke(this, EventArgs.Empty)

 

C# 6.0:Null – Conditional 操作符

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.