2016年6月28日 星期二

[C#]?? Null 聯合運算子

?? 運算子稱為 null 聯合運算子.
如果運算元不是 null,則會傳回左方運算元,否則傳回右方運算元.
如果運算元不屬於聯合運算子.則無法使用.

EX:
1.  int? x = null;       
       Response.Write("x:" + x);       
       ==>回傳空值

2. int y = x ?? -1;       
      Response.Write("y:" + y );    
      ==>x為空值.y就回傳-1

3.   int? a = 123;
      int b = a ?? 456;
      Response.Write("b:" + b + "<br/>");
      ==>a為123.y就回傳123

4.   int c = 123;
      int d = c ?? 456;  ==>error.無法將運算子'??'套用至int和int的運算元
      Response.Write("d:" + d + "<br/>");
      

運用
1.未定義,也就是值為 null的狀態. 可在宣告時使用.
2.如果使用轉換型別,而資料又剛好是為 null 但尚未定義,會擲回 InvalidOperationException 例外狀況,使用 ?? 運算子可解決這問題。

參考網址:https://msdn.microsoft.com/zh-tw/library/ms173224.aspx

沒有留言:

張貼留言