zoukankan      html  css  js  c++  java
  • .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;
            }
    

      

  • 相关阅读:
    HTML和CSS 基本要点必看
    CSS
    六个选择器
    HTML初级课程 (自学可懂)
    this
    1.作用域链
    js if 语句
    js数据类型
    ifelse语句
    三元运算符
  • 原文地址:https://www.cnblogs.com/dragon-L/p/3711644.html
Copyright © 2011-2022 走看看