第十六節:語法總結(3)(C#6.0和C#7.0新語法)

一. C# 6.0 新語法ide

1. 自動屬性初始化能夠賦值函數

 1     /// <summary>
 2     /// 自動屬性初始化
 3     /// </summary>
 4     public class UserInfor
 5     {
 6         public string userId { get; set; } = "123456";
 7 
 8         public string userName { get; set; } = "lmr";
 9 
10     }
11    {
12        Console.WriteLine("------------------------- 1. 自動屬性初始化能夠賦值----------------------------");
13        UserInfor uInfor = new UserInfor();
14        Console.WriteLine($"id={uInfor.userId},userName={uInfor.userName}");
15    }

2. 字符串嵌入值【$配合{}使用】測試

  特別注意:{}中若是有業務計算須要配合()使用spa

1    {
2                 Console.WriteLine("------------------------- 2. 字符串嵌入值【$配合{}使用】----------------------------");
3                 UserInfor uInfor2 = new UserInfor();
4                 Console.WriteLine($"名字爲:{uInfor2.userName}");
5                 //表明要輸入一個括號{}
6                 Console.WriteLine($"名字爲:{{{uInfor2.userName}}}");
7                 //{}中若是有業務計算須要配合()使用
8                 Console.WriteLine($"{(uInfor2.userName != "lmr" ? "小鮮肉" : "老鮮肉")}");
9    }

3. 能夠在命名空間出使用static聲明靜態類code

 

1 {
2                 Console.WriteLine($"-------------------------3.能夠在命名空間出使用static聲明靜態類-------------------------");
3                 Console.WriteLine($"以前的使用方式: {Math.Pow(4, 2)}");
4                 Console.WriteLine($"導入後可直接使用方法: {Pow(4, 2)}");
5 }

4. 空值運算符(?) orm

  不須要判斷是否爲空了.對象

1  {
2                 Console.WriteLine($"-------------------------4. 空值運算符-------------------------");
3                 int? iValue = 10;
4                 Console.WriteLine(iValue?.ToString());//不須要判斷是否爲空
5                 string name = null;
6                 Console.WriteLine(name?.ToString());
7 }

5. 對象初始化blog

  能夠直接給字典類型經過相似「索引」的形式賦值 (原先是經過Add方法賦值)索引

 1  {
 2                 Console.WriteLine($"-------------------------5. 字典對象初始化-------------------------");
 3                 Dictionary<string, string> dicList = new Dictionary<string, string>()
 4                 {
 5                     ["1"] = "ypf1",
 6                     ["2"] = "ypf2",
 7                     ["3"] = "ypf3"
 8                 };
 9                 Dictionary<string, string> dicList2 = new Dictionary<string, string>()
10                  {
11                      { "1","lmr1"},
12                      { "2","lmr2"},
13                      { "3","lmr3"}
14                  };
15                 foreach (var item in dicList)
16                 {
17                     Console.WriteLine("key:{0},value:{1}", item.Key.ToString(), item.Value.ToString());
18                 }
19                 foreach (var item in dicList2)
20                 {
21                     Console.WriteLine("key:{0},value:{1}", item.Key.ToString(), item.Value.ToString());
22                 }
23             }

6. 異常過濾器增長when判斷條件字符串

  只有符合when裏的條件,才能進入catch,若是不知足的話,直接代碼報錯,不能拋異常

 1   {
 2                 Console.WriteLine("-------------------------6. 異常過濾器增長when判斷條件-------------------------");
 3                 int epCheck = 100;
 4                 try
 5                 {
 6                     int.Parse("ypf");
 7                 }
 8                 catch (Exception e) when (epCheck > 11)
 9                 {
10                     Console.WriteLine(e.Message);
11                 }
12 }

7. nameof表達式

  把實例轉換成同名的字符串

1  {
2                 Console.WriteLine("-------------------------7. nameof表達式-------------------------");
3                 UserInfor userInfor = new UserInfor();
4                 Console.WriteLine(nameof(userInfor));
5 }

8. 在catch和finally語句塊裏使用await(暫不介紹,不經常使用)

9. 在屬性或方法上使用Lambada表達式

  ①:方法針對於只有一行的方法

  ②:屬性經過Lambda的形式進行賦值

   public class UserInfor
    {
        public string userId { get; set; } = "123456";

        public string userName { get; set; } = "lmr";

        /// <summary>
        /// Lambda類型的方法
        /// </summary>
        public void LambdaPrint() => Console.WriteLine("我是Lambda類型的方法");

        public string userSex => string.Format("");
    }
 {
                Console.WriteLine("-------------------------9.在屬性或方法上使用Lambada表達式-------------------------");
                UserInfor userInfor = new UserInfor();
                userInfor.LambdaPrint();
                Console.WriteLine($"userSex的值爲:{userInfor.userSex}");
}

 

二. C# 7.0 新語法

1. out參數的改進

  在C#7.0以前, out參數使用前必須先聲明,而後傳入方法中,在C#7.0後能夠直接在傳入方法的時候進行聲明。

 1         /// <summary>
 2         /// out參數的改進
 3         /// </summary>
 4         /// <param name="x"></param>
 5         /// <param name="y"></param>
 6         public void DoNoting(out int x, out int y)
 7         {
 8             x = 1;
 9             y = 2;
10         }
11         {
12             Console.WriteLine("--------------------1-out參數的改進------------------------");
13             SevenEdition s = new SevenEdition();
14             s.DoNoting(out int x, out int y);
15             Console.WriteLine(x + y);
16          }

2. 元組(Tuples)

  ①:須要經過nuget安裝這個System.ValueTuple

  ②:元組建立的三種方式:語法糖、Create靜態方法、構造函數 (默認狀況下是經過Item一、Item2 。。。)

  ③:指定元祖命名:能夠經過左邊指定,也能夠經過右邊指定

  ④:將元祖應用於方法中返回值,即一個方法能夠返回多種不一樣類型的值,不須要封裝實體便可以實現。

 1         /// <summary>
 2         /// 默認元組命名
 3         /// </summary>
 4         /// <returns></returns>
 5         public (int, string, string) TupleWay1()
 6         {
 7             return (1, "ypf1", "ypf2");
 8         }
 9         /// <summary>
10         /// 指定元祖命名
11         /// </summary>
12         /// <returns></returns>
13         public (int m, string n, string k) TupleWay2()
14         {
15             return (1, "ypf1", "ypf2");
16         }
17            {
18                 Console.WriteLine("--------------------2-元組(Tuples)------------------------");
19                 //1. 建立元組的三種形式
20                 Console.WriteLine("--------------------1. 建立元組的三種形式------------------------");
21                 var tuple1 = (1, 2);   //語法糖
22                 var tuple2 = ValueTuple.Create("ypf", "lmr");  //Create靜態方法
23                 var tuple3 = new ValueTuple<int, string>(12, "ypf12");  //構造函數
24                 Console.WriteLine($"tuple1的兩個值爲:{tuple1.Item1}和{tuple1.Item2}");
25                 Console.WriteLine($"tuple1的兩個值爲:{tuple2.Item1}和{tuple2.Item2}");
26                 Console.WriteLine($"tuple1的兩個值爲:{tuple3.Item1}和{tuple3.Item2}");
27 
28                 //2. 指定元祖命名
29                 Console.WriteLine("--------------------2. 指定元祖命名------------------------");
30                 (int m, string n) tuple4 = (100, "erp");  //左邊命名
31                 Console.WriteLine($"tuple4的兩個值爲:{tuple4.m}和{tuple4.n}");
32                 var tuple5 = (one: 250, two: "spz");     //右邊命名
33                 Console.WriteLine($"tuple5的兩個值爲:{tuple5.one}和{tuple5.two}");
34 
35                 //3. 元祖應用於方法中返回值
36                 Console.WriteLine("--------------------3. 元祖應用於方法中返回值------------------------");
37                 SevenEdition s = new SevenEdition();
38                 //默認命名
39                 var result1 = s.TupleWay1();
40                 Console.WriteLine($"返回值有:{result1.Item1}、{result1.Item2}、{result1.Item3}");
41                 //指定命名
42                 var result2 = s.TupleWay2();
43                 Console.WriteLine($"返回值有:{result2.m}、{result2.n}、{result2.k}");
44 
45             }

3. 局部函數

  即在{}中聲明一個函數,只有{}中能使用

1   {
2                 Console.WriteLine("--------------------3-局部函數------------------------");
3                 DoSome();
4                 void DoSome()
5                 {
6                     Console.WriteLine("我是局部函數");
7                 }
8   }

4. 模式的比較和匹配

  ①:is的新模式。

    首先補充一個概念:拆箱和裝箱

    拆箱是將引用類型→值類型 (object ,class均爲引用類型)

    裝箱是將值類型→引用類型

  案例:有一個object類型的變量a,若是它是int類型,則+10賦值給m,並輸出m的值,下面看新老用法比較。

 1  {
 2                     Console.WriteLine("--------------------4-模式比較(is)------------------------");
 3                     object a = 9;
 4                     //老寫法
 5                     if (a is int)
 6                     {
 7                         int b = (int)a;  //拆箱
 8                         int c = b + 10;
 9                         Console.WriteLine($"老寫法c的值爲:{c}");
10                     }
11                     //新寫法
12                     if (a is int m)   //這裏的a直接拆箱爲m
13                     {
14                         int c = m + 10;
15                         Console.WriteLine($"新寫法c的值爲:{c}");
16                     }
17 }

  ②:switch-case中能夠自定義參數類型

  傳統狀況,全部的case中必須是同類型的;而在C# 7.0 新版本中,case中能夠不一樣類型,即Swich中能夠傳入任何類型,而後經過case中進行對應匹配,這就叫作模式匹配。

 1  /// <summary>
 2         /// 單一類型
 3         /// </summary>
 4         /// <param name="m"></param>
 5         /// <returns></returns>
 6         public dynamic SwitchWay1(string m)
 7         {
 8             dynamic data;
 9             switch (m)
10             {
11                 case "ypf1":
12                     data = m + "lmr1";
13                     break;
14                 case "ypf2":
15                     data = m + "lmr2";
16                     break;
17                 default:
18                     data = "spz00000";
19                     break;
20             }
21             return data;
22         }
23 
24         /// <summary>
25         /// 多種類型
26         /// </summary>
27         /// <param name="m"></param>
28         /// <returns></returns>
29         public dynamic SwitchWay2(object m)
30         {
31             dynamic data;
32             switch (m)
33             {
34                 case int a when a > 10:
35                     data = a + 10;
36                     break;
37                 case int b:
38                     data = b + 100;
39                     break;
40                 case String c:
41                     data = c + "mmmmmmmmmmmmmmm";
42                     break;
43                 default:
44                     data = "spz00000";
45                     break;
46             }
47             return data;
48         }
View Code
 1    {
 2                     Console.WriteLine("--------------------4-模式匹配(switch-case)------------------------");
 3                     SevenEdition sE = new SevenEdition();
 4                     //老用法
 5                     var data1 = sE.SwitchWay1("ypf1");
 6                     Console.WriteLine($"類型爲:{data1.GetType()},值爲:{data1}");
 7                     //新用法
 8                     var data2 = sE.SwitchWay2(1);
 9                     Console.WriteLine($"類型爲:{data2.GetType()},值爲:{data2}");
10 
11                     var data3 = sE.SwitchWay2(11);
12                     Console.WriteLine($"類型爲:{data3.GetType()},值爲:{data3}");
13 
14                     var data4 = sE.SwitchWay2("ypf1");
15                     Console.WriteLine($"類型爲:{data4.GetType()},值爲:{data4}");
16 
17  }

 

5. 數字文本語法的改寫

   好比10000000 能夠寫成10_000_000 ,方便識別。

 {
                Console.WriteLine("--------------------5-數字文本語法的改寫------------------------");
                long a = 10000000;
                long b = 10_000_000;
                Console.WriteLine($"a的值爲:{a},b的值爲:{b}");

 }

6. 補充一些特殊地方也能夠寫異常表達式 (不詳細測試了)

   好比:條件表達式(? :)、null合併運算符(??)、一些Lambda

  eg:private string _name = GetName() ?? throw new ArgumentNullException(nameof(GetName));

 

 

 

 

相關文章
相關標籤/搜索