.net 空接合操作符 ??

  C# 提供了一个所谓的 ”空接合操作符“ - 即??操作符,他要获取两个操作数。

  假如左边的操作数部位null,就返回这个操作数。如果左边的操作数为null就返回右边。

     空接合操作符一个妙处在于,它既能用于引用类型,也能用于空值类型。

        static void Main(string[] args)
        {
            Int32? b = null;
            
            //下面这行代码等价于
            //x = (b.HasValue) ? b.Value : 123;
            Int32 x = b ?? 123;

            string temp = "";
            string fileTemp = (temp == null) ? temp : "Untitled";
            string fileTemp1 = GetName() ?? "Untitled"; 

            Console.ReadLine();
        }

        public static string GetName()
        {
            return null;
        }

 在看下一个例子。

        static void Main(string[] args)
        {
      
            //f1是否不 f简洁很多呢。
            Func<string> f1 = () => SomeMethod() ?? "Untitled";
            Func<string> f = () => { var temps = SomeMethod(); return temps != null ? temps : "Untitled"; };

            //第二个 在复合情形中的用法 
            Func<string> s1 = () => SomeMethod() ?? SomeMethod2() ?? "Untitled";
            //比下面的代码更容易阅读些
            string s;
            string sm1 = SomeMethod1();
            if (sm1 != null)
            {
                s = sm1;
            }
            else
            {
                string sm2 = SomeMethod2();
                if (sm2 != null)
                    s = sm2;
                else
                    s = "Untitled";
            }
            Console.ReadLine();
        }

       public static string SomeMethod()
        {
            return null;
        }
        public static string SomeMethod1()
        {
            return null;
        }
        public static string SomeMethod2()
        {
            return null;
        }

  

posted @ 2014-05-06 15:36  dragon.net  阅读(424)  评论(0编辑  收藏  举报