1. Out引數
#region 1.Out引數 var str = "2"; ///之前的寫法 { int iValue; //將str轉化成int型別,若轉化成功,將值賦給iValue,并回傳true;若轉化失敗,回傳false, if (int.TryParse(str, out iValue)) { WriteLine(iValue); } } //C#7的寫法 { if (int.TryParse(str, out int iValue)) { WriteLine(iValue); } //或者 if (int.TryParse(str, out var vValue)) { WriteLine(iValue); } } #endregion
2. 模式
#region 2.模式 pattern { WriteLine("C#7_2.模式 pattern:"); this.PrintStars(null); this.PrintStars(2); }
/// <summary> /// 具有模式的 IS 運算式 /// </summary> private void PrintStars(Object oValue) { if (oValue is null) return;// 常量模式 "null" if (!(oValue is int iValue)) return;// 型別模式 定義了一個變數 "int i" WriteLine(iValue); WriteLine(new string('*', iValue)); }
3. Swith
#region 3. Swith { WriteLine("C#7_3. Swith新語法:"); this.Swith("wang"); this.Swith("Max"); this.Swith("wangMax"); this.Swith(null); this.Swith(""); } #endregion
/// <summary> /// 可以設定任何型別的 Switch 陳述句(不只是原始型別) /// 模式可以用在 case 陳述句中 /// Case 陳述句可以有特殊的條件 /// </summary> private void Swith(string sValue) { int iValue = https://www.cnblogs.com/wangwangwangMax/p/1; switch (sValue) { case string s when s.Length >= 4: WriteLine("s"); break; case "Max" when sValue.Length > 2: WriteLine(sValue); break; default: WriteLine("default"); break; case null: WriteLine("null"); break; } }
4. 數字分隔符【每隔3位+"_"】
#region 4.數字分隔符【每隔3位+"_"】 long lValue =https://www.cnblogs.com/wangwangwangMax/p/ 100_000_000; WriteLine(lValue); #endregion
5. 區域函式
#region 5. 區域函式 { WriteLine("C#7_6. 區域函式:"); Add(3); int Add(int i) { WriteLine(2 + i); return i; } } #endregion
6. 元組
#region 6.元組 { var result = this.LookupName(1); WriteLine(result.Item1); WriteLine(result.Item2); WriteLine(result.Item3); } { var result = this.LookupNameByName(1); WriteLine(result.first); WriteLine(result.middle); WriteLine(result.last); WriteLine(result.Item1); WriteLine(result.Item2); WriteLine(result.Item3); } #endregion
/// <summary> /// System.ValueTuple 需要安裝這個nuget包 /// </summary> /// <param name="id"></param> /// <returns></returns> private (string, string, string) LookupName(long id) // tuple return type { return ("first", "middle", "last"); } private (string first, string middle, string last) LookupNameByName(long id) // tuple return type { return ("first", "middle", "last"); //return (first: "first", middle: "middle", last: "last"); }
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/228221.html
標籤:C#
上一篇:C#6 的一些新語法
下一篇:DBHelper助手
