C#7.0新语法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C#7.0新语法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2753字,纯文字阅读大概需要4分钟。
内容图文
一、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 /// <summary> 2 /// 具有模式的 IS 表达式 3 /// </summary> 4 /// <param name="o"></param> 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<10才会输出Tom 7 Console.WriteLine("Tom"); 8 break; 9 case "Joe" when text.Length < 10: //text="Joe"且text的长度<10才会输出Joe 10 Console.WriteLine("Joe"); 11 break; 12 case string s when s.Length > 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 /// <summary> 2 /// 使用默认参数名称 3 /// </summary> 4 /// <param name="id"></param> 5 /// <returns></returns> 6 private (string, string, string) LookupName(long id) // tuple return type 7 { 8 return ("first", "middle", "last"); 9 } 10 11 /// <summary> 12 /// 不使用默认参数名称 13 /// </summary> 14 /// <param name="id"></param> 15 /// <returns></returns> 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}");
原文:https://www.cnblogs.com/asdyzh/p/9819719.html
内容总结
以上是互联网集市为您收集整理的C#7.0新语法全部内容,希望文章能够帮你解决C#7.0新语法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。