#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
#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)); }
#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 = 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; } }
#region 4.數字分隔符【每隔3位+"_"】 long lValue = 100_000_000; WriteLine(lValue); #endregion
#region 5. 局部函數 { WriteLine("C#7_6. 局部函數:"); Add(3); int Add(int i) { WriteLine(2 + i); return i; } } #endregion
#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"); }