C#7.0 新增功能
C# 7.0 向 C# 语言添加了许多新功能
支持?
out ?参数的现有语法已在此版本中得到改进。?现在可以在方法调用的参数列表中声明?out ?变量,而不是编写单独的声明语句:
if (int.TryParse(input,out int result)) Console.WriteLine(result); else Console.WriteLine("Could not parse input");
为清晰明了,可能需指定?
out ?变量的类型,如上所示。?但是,该语言支持使用隐式类型的局部变量:
if (int.TryParse(input,out var answer)) Console.WriteLine(answer); else Console.WriteLine("Could not parse input");
C# 为用于说明设计意图的类和结构提供了丰富的语法。?但是,这种丰富的语法有时会需要额外的工作,但益处却很少。?你可能经常编写需要包含多个数据元素的简单结构的方法。为了支持这些方案,已将元组 添加到了 C#。?元组是包含多个字段以表示数据成员的轻量级数据结构。?这些字段没有经过验证,并且你无法定义自己的方法
可以通过为每个成员赋值来创建元组,并可选择为元组的每个成员提供语义名称:
(string Alpha,string Beta) namedLetters = ("a","b"); Console.WriteLine($"{namedLetters.Alpha},{namedLetters.Beta}");
在进行元组赋值时,还可以指定赋值右侧的字段的名称: var alphabetStart = (Alpha: "a",Beta: "b"); Console.WriteLine($"{alphabetStart.Alpha},{alphabetStart.Beta}"); 在某些时候,你可能想要解包从方法返回的元组的成员。?可通过为元组中的每个值声明单独的变量来实现此目的。?这种解包操作称为解构元组 : (int max,int min) = Range(numbers); Console.WriteLine(max); Console.WriteLine(min); 还可以为 .NET 中的任何类型提供类似的析构。?编写? public class Point { public double X { get; } public double Y { get; } public Point(double x,double y) => (X,Y) = (x,y); public void Deconstruct(out double x,out double y) => (x,y) = (X,Y); } 可以通过向元组分配? var p = new Point(3.14,2.71); 可在元组相关文章中深入了解有关元组的详细信息。 通常,在进行元组解构或使用? 在以下方案中支持弃元:
以下示例定义了? 1 using System; 2 using System.Collections.Generic; 3 4 public class Example 5 { 6 public static void Main() 7 { 8 var (_,_,pop1,pop2) = QueryCityDataForYears("New York City",1960,2010); 9 10 Console.WriteLine($"Population change,1960 to 2010: {pop2 - pop1:N0}"); 11 } 12 13 private static (string,double,int,int) QueryCityDataForYears(string name,int year1,int year2) 14 { 15 int population1 = 0,population2 = 0; 16 double area = 0; 17 18 if (name == "New York City") { 19 area = 468.48; 20 if (year1 == 1960) { 21 population1 = 7781984; 22 } 23 if (year2 == 2010) { 24 population2 = 8175133; 25 } 26 return (name,area,year1,population1,year2,population2); 27 } 28 29 return ("",0,0); 30 } 31 } 32 // 输出结果: 33 // Population change,1960 to 2010: 393,149 有关详细信息,请参阅弃元。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- XML基础
- ruby-on-rails – rails 4 collection_select多个嵌套属性未
- objective-c – 使用窗口关闭按钮完全关闭OS X应用程序
- C中的魔法用这个表达式x = y – x(y = x)[复制]
- 基于vue组件实现猜数字游戏
- c – 从boost :: shared_ptr返回C字符串
- 《从零开始学Swift》学习笔记(Day 32)――计算属性
- c-std :: piecewise_linear_distribution在VS2012下不工作?
- 解决flex rpc发送失败,老发送到WebContent问题
- ruby-on-rails – 解决Rails资产管道中依赖顺序的最佳方法?