C#7.0新语法
2021-07-05 16:12
阅读:755
一、out输出参数
在以前使用out输出参数的时候,必须先定义变量,然后才能使用,例如:
先定义一个方法,方法参数是out类型的输出参数:
1 private void DoNoting(out int x, out int y)
2 {
3 x = 1;
4 y = 2;
5 }
以前版本的写法:
1 // 必须先定义i、j,才能使用out参数
2 int i = 0;
3 int j = 0;
4 this.DoNoting(out i, out j);
5 Console.WriteLine($"i+j={i+j}");
在C#7.0中,可以不用先定义,就能够直接使用了:
1 this.DoNoting(out int x, out int y);
2 Console.WriteLine($"x+y={x + y}");
3 this.DoNoting(out var l, out var m);
结果:

二、模式

1 ///2 /// 具有模式的 IS 表达式 3 /// 4 /// 5 public void PrintStars(object o) 6 { 7 if (o is null) return; // 常量模式 "null" 8 if (!(o is int i)) return; // 类型模式 定义了一个变量 "int i" i的值就是o的值 相当于is类型判断 9 Console.WriteLine($"i={i}"); 10 }

使用方法:
1 this.PrintStars(null); 2 this.PrintStars(3);
结果:

除了可以像上面那样使用外,还可以使用下面的方式:

1 private void Switch(string text)
2 {
3 int k = 100;
4 switch (text)
5 {
6 case "Tom" when k > 10: // text="Tom"且k 7://模式 定义变量s,s就是text的值
13 Console.WriteLine(s);
14 break;
15 default:
16 Console.WriteLine("default");
17 break;
18 case null:
19 Console.WriteLine("null");
20 break;
21 }
22 }

调用:
1 this.Switch(null);
2 this.Switch("TomTomKevin");
3 this.Switch("JoeForest");

三、元组
先来看下面的两个方法:

1 ///2 /// 使用默认参数名称 3 /// 4 /// 5 ///6 private (string, string, string) LookupName(long id) // tuple return type 7 { 8 return ("first", "middle", "last"); 9 } 10 11 /// 12 /// 不使用默认参数名称 13 /// 14 /// 15 ///16 private (string first, string middle, string last) LookupNameByName(long id) // tuple return type 17 { 18 return ("first", "middle", "last"); 19 //return (first: "first", middle: "middle", last: "last"); 20 }

调用:

1 // 使用默认参数名称:Item1、Item2、Item3 2 Console.WriteLine($"使用默认参数名称"); 3 var result = this.LookupName(1); 4 Console.WriteLine(result.Item1); 5 Console.WriteLine(result.Item2); 6 Console.WriteLine(result.Item3); 7 // 不使用默认参数名称 8 Console.WriteLine($"不使用默认参数名称"); 9 var result2 = this.LookupNameByName(1); 10 Console.WriteLine(result2.first); 11 Console.WriteLine(result2.middle); 12 Console.WriteLine(result2.last); 13 // 也可以使用默认参数名称 14 Console.WriteLine($"也可以使用默认参数名称"); 15 Console.WriteLine(result2.Item1); 16 Console.WriteLine(result2.Item2); 17 Console.WriteLine(result2.Item3);

结果:

四、数字分割
如果数字太长,可以按照一定的位数用“_”进行分割,例如:
1 long big = 100_000_0000;
2 Console.WriteLine($"big={big}");

评论
亲,登录后才可以留言!