ASP.NETCore2C#7.0新语法
1.out参数,不用声明x、y
private void DoNoting(out int x, out int y) { x = 1; y = 2; } {//调用 this.DoNoting(out int x, out int y); Console.WriteLine(x + y); this.DoNoting(out var l, out var m); }
2.模式
/// <summary>
/// 具有模式的 IS 表达式
/// </summary>
/// <param name="o"></param>
public void PrintStars(object o)
{
if (o is null) return; // 常量模式 "null"
if (!(o is int i)) return; // 类型模式 定义了一个变量 "int i"
Console.WriteLine(new string('*', i));
}
/// <summary>
/// 可以设定任何类型的 Switch 语句(不只是原始类型)
/// 模式可以用在 case 语句中
/// Case 语句可以有特殊的条件
/// </summary>
/// <param name="text"></param>
private void Switch(string text)
{
int k = 100;
switch (text)
{
case "RichardRichard" when k > 10:
Console.WriteLine("RichardRichard");
break;
case "Richard" when text.Length < 10:
Console.WriteLine("Richard");
break;
case string s when s.Length > 7://模式
Console.WriteLine(s);
break;
default:
Console.WriteLine("default");
break;
case null:
Console.WriteLine("null");
break;
}
}
this.PrintStars(null);
this.PrintStars(3);
this.Switch(null);
this.Switch("RichardRichard");
this.Switch("Richard");
3.元组,例如分页需要返回分页信息使用
/// <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"); } {//调用 var result = this.LookupName(1); Console.WriteLine(result.Item1); Console.WriteLine(result.Item2); Console.WriteLine(result.Item3); } { var result = this.LookupNameByName(1); Console.WriteLine(result.first); Console.WriteLine(result.middle); Console.WriteLine(result.last); Console.WriteLine(result.Item1); Console.WriteLine(result.Item2); Console.WriteLine(result.Item3); }
4.局部函数
{ Add(3); int Add(int k)//闭合范围内的参数和局部变量在局部函数的内部是可用的,就如同它们在 lambda 表达式中一样。 { return 3 + k; } }
5.数字分隔号,每三位可以加一个下划线
long big = 100_000;
本文来自博客园,作者:不朽阁主,转载请注明原文链接:https://www.cnblogs.com/sunff/p/13257904.html
浙公网安备 33010602011771号