我们登上的并非我们所选择的舞台,演出并非我们所选择的剧本。-- 爱比克泰|

石起起

园龄:1年10个月粉丝:1关注:0

2025-02-05 17:42阅读: 82评论: 0推荐: 0

C# 版本 6 新增特性

C# 6.0 版

发布时间:2015 年 7 月

版本 6.0 随 Visual Studio 2015 一起发布,发布了很多使得 C# 编程更有效率的小功能。 以下介绍了部分功能:

其他新功能包括:

  • 索引初始化表达式
  • Catch/Finally 块中的 Await
  • 仅限 getter 属性的默认值

如果整体看待这些功能,你会发现一个有趣的模式。 在此版本中,C# 开始消除语言样本,让代码更简洁且更具可读性。 所以对喜欢简洁代码的用户来说,此语言版本非常成功。

除了发布此版本,他们还做了另一件事,虽然这件事本身与传统的语言功能无关。 他们发布了 Roslyn 编译器即服务。 C# 编译器现在是用 C# 编写的,你可以使用编译器作为编程工作的一部分。


参考文章:
C#6.0 新增功能 - 张传宁 - 博客园
C#6.0新特性学习_c# 6.0-CSDN博客


笔记

静态导入 using static

using static System.Console; 
using static System.Math; // 可以直接使用该类下的静态成员

异常筛选器 when 关键字

catch (ExceptionType [e]) when (expr)

// 👇 when 指定一个条件表达式,为true时才会捕捉该异常
catch (HttpRequestException e) when (e.Message.Contains("301")) 
{ return "Site Moved"; }  
catch (Exception e) when (e is ArgumentException || e is DivideByZeroException) 
{ Console.WriteLine($"Processing failed: {e.Message}"); }

自动属性

public string FirstName { get; set; } = string.Empty;  // 声明属性的时候为属性设定初始值

表达式成员 member => expression;

// 该方法成员使用了lambda表达式
// 该条规则对属性和方法都适用
public override string ToString() => $"{fname} {lname}".Trim();

Null 传播器 ?. 和 ?[]

如果 a 的计算结果为 null,则 a?.x 或 a?[x] 的结果为 null
如果 a 的计算结果为非 null,则 a?.x 或 a?[x] 的结果将分别与 a.x 或 a[x] 的结果相同。

a?.x // 成员访问
a?[x] // 元素访问
first = person?.FirstName ?? "Unspecified"; // 与 “null合并” 运算符一起使用
// 👆 他们都会执行短路返回

字符串内插 $

Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");

nameof 运算符

nameof 表达式可生成变量、类型或成员的名称作为字符串常量。

Console.WriteLine(nameof(System.Collections.Generic)); // output: Generic 
Console.WriteLine(nameof(List<int>)); // output: List 
Console.WriteLine(nameof(List<int>.Count)); // output: Count 
Console.WriteLine(nameof(List<int>.Add)); // output: Add 

List<int> numbers = new List<int>() { 1, 2, 3 }; 
Console.WriteLine(nameof(numbers)); // output: numbers 
Console.WriteLine(nameof(numbers.Count)); // output: Count 
Console.WriteLine(nameof(numbers.Add)); // output: Add

索引初始化表达式

private Dictionary<int, string> webErrors = new Dictionary<int, string>
{
    [404] = "Page not Found", // 通过索引直接指定值
    [302] = "Page moved, but left a forwarding address.",
    [500] = "The web server can't come out to play today."
};

Catch/Finally 块中的 Await

try     
{
	var responseText = await streamTask;
	return responseText;
} catch (System.Net.Http.HttpRequestException e) when (e.Message.Contains("301"))
{
	await logError("Recovered from redirect", e);  // 👈
	return "Site Moved";
}
finally
{
	await logMethodExit();  // 👈
	client.Dispose();
}

仅限 getter 属性的默认值

public string LastName {get;} = "Hello"; // 只读的属性也可以有初始化语句,并且,只读的属性可在构造器中进行赋值

本文作者:石起起

本文链接:https://www.cnblogs.com/myshiqiqi/p/18699879

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   石起起  阅读(82)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起