[C#] ?? 運算子

  • 3898
  • 0

摘要:[C#] ?? 運算子

之前有介紹過 可為 Null 的型別 ,這邊繼續玩弄【 ?? 】 運算子。

Introduction

先附上 MSDN 參考連結:msdn.microsoft.com/zh-tw/library/ms173224.aspx

?? 運算子稱為 null 聯合運算子,用來定義可為 null 的實值型別和參考型別的預設值。運算子如果不是 null 就會傳回左方運算元,否則傳回右運算元。

 

Example

    class Program {

        static int? GetNullableInt() {
            return null;
        }

        static string GetStringValue() {
            return null;
        }

        static float? GetNullableFloat() {
            return null;
        }

        private static int g; //類別層級變數可不指定初值。

        static void Main(string[] args) {

            // ?? operator example.
            int? x = null;
            

            // y = x, unless x is null, in which case y = -1.
            int y = x ?? -1;

            // Assign i to return value of method, unless
            // return value is null, in which case assign
            // default value of int to i.
            int i = GetNullableInt() ?? default(int);


            float f = GetNullableFloat() ?? default(float);
            string ss = string.Empty;
            string s = GetStringValue();
          


            Console.WriteLine("x = " + x);
            Console.WriteLine("g = " + g);
            Console.WriteLine("y = " + y);
            Console.WriteLine("i = " + i);
            Console.WriteLine("f = " + f);
            Console.WriteLine("s = " + s);
            Console.WriteLine("ss = " + ss);

            // ?? also works with reference types. 
            // Display contents of s, unless s is null, 
            // in which case display "Unspecified".]
            Console.WriteLine(s ?? "Unspecified");
            Console.Read();
        }




    }

 

 

注意事項

類別層級的變數宣告與區域變數的宣告,在設定初始值是有個別限制的(因為我也是最近才被提醒的)。

觀察上述例子,觀察變數的值,我想我們都能體會的。

三小俠  小弟獻醜,歡迎指教