回顾C#各版本特性
C# 6.0
- Read-only auto-properties(只读自动属性)
以前版本,声明只读属性时,示例:
public string FirstName { get; private set; }
public string LastName { get; private set; }
6.0,不显示写setter即是只读属性,但属性也只能在构造函数中初始化了
示例:
public string FirstName { get; }
public string LastName { get; }
- Auto-Property Initializers(自动属性初始化)
以前版本,属性的初始化需要放在构造函数中进行,6.0可以在属性声明时初始化
示例:
public ICollection<double> Grades { get; } = new List<double>();
public Standing YearInSchool { get; set;} = Standing.Freshman;
- Expression-bodied function members(表达式体函数成员)
6.0可以直接在函数体使用表达式,这简化一些很简单的函数的书写(仅支持使用只读的属性)
示例:
public override string ToString() => $"{LastName}, {FirstName}";
public string FullName => $"{FirstName} {LastName}";
- using static
可以直接引用具体对象,然后在本地直接使用其静态函数。
以前:
using System; namespace TestCsharp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("ok");
}
}
}
6.0版本:
using static System.Console; namespace TestCsharp
{
class Program
{
static void Main(string[] args)
{
WriteLine("ok");
}
}
}
- Null-conditional operators(空条件操作符)
更加简化的空对象判断,不为空可直接访问其属性
以前先判断对象不为空,再访问属性:
class Program
{
static void Main(string[] args)
{
Person person = new Person(); var first = person == null ? "" : person.FirstName; Console.WriteLine(first);
}
} class Person
{
public string FirstName { get; set; } public Person()
{
FirstName = "init name";
}
}
6.0版本,直接替换属性访问 . 为 ?. 一步完成判断和访问:
class Program
{
static void Main(string[] args)
{
Person person = new Person(); var first = person?.FirstName; Console.WriteLine(first);
}
} class Person
{
public string FirstName { get; set; } public Person()
{
FirstName = "init name";
}
}
- String interpolation(字符串插值)
以前,字符串拼接时,要使用string.Format,示例:
public string FullName
{
get
{
return string.Format("Name is{0} {1}", FirstName, LastName);
}
}
6.0可以直接使用$代替string.Format,示例:
public string FullName
{
get
{
return $"Name is {FirstName}{LastName}";
}
}
进一步,可以在其中使用 : 标示格式化风格,如下,F2标识两位小数,示例:
public string GetGradePointPercentage() =>
$"Name: {LastName}, {FirstName}. G.P.A: {Grades.Average():F2}";
- Exception Filters(异常过滤器)
增加过滤器,直接在异常捕获后就可以进行相应的判断
以前:
public static async Task<string> MakeRequest()
{
var client = new System.Net.Http.HttpClient();
var streamTask = client.GetStringAsync("https://localHost:10000");
try {
var responseText = await streamTask;
return responseText;
} catch (System.Net.Http.HttpRequestException e)
{
if (e.Message.Contains("301"))
return "Site Moved";
else
throw;
}
}
6.0版本,在外部使用when进行条件匹配:
public static async Task<string> MakeRequest()
{
var client = new System.Net.Http.HttpClient();
var streamTask = client.GetStringAsync("https://localHost:10000");
try {
var responseText = await streamTask;
return responseText;
} catch (System.Net.Http.HttpRequestException e) when (e.Message.Contains("301"))
{
return "Site Moved";
}
}
- nameof Expressions
主要场景是异常中提供名字:
if (IsNullOrWhiteSpace(lastName))
throw new ArgumentException(message: "Cannot be blank", paramName: nameof(lastName));
还有就是MVVM中INotifyPropertyChanged实现:
public string LastName
{
get { return lastName; }
set
{
if (value != lastName)
{
lastName = value;
PropertyChanged?.Invoke(this,
new PropertyChangedEventArgs(nameof(LastName)));
}
}
}
private string lastName;
- Await in Catch and Finally blocks
版本5中对await的使用做了一些限制,6中去除了这些限制。
示例:
public static async Task<string> MakeRequestAndLogFailures()
{
await logMethodEntrance();
var client = new System.Net.Http.HttpClient();
var streamTask = client.GetStringAsync("https://localHost:10000");
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();
}
}
- Index Initializers
之前版本示例:
private List<string> messages = new List<string>
{
"Page not Found",
"Page moved, but left a forwarding address.",
"The web server can't come out to play today."
};
6.0版本:
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."
};
- Extension Add methods in collection inializers
假定有以下一个类,Enroll添加对象到集合中:
public class Enrollment : IEnumerable<Student>
{
private List<Student> allStudents = new List<Student>(); public void Enroll(Student s)
{
allStudents.Add(s);
} public IEnumerator<Student> GetEnumerator()
{
return ((IEnumerable<Student>)allStudents).GetEnumerator();
} IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<Student>)allStudents).GetEnumerator();
}
}
以前版本,你只能过显示调用Enroll方法,一个个添加对象。
var classList = new Enrollment();
classList.Enroll(new Student("Lessie", "Crosby"));
6.0增加了Add方法,允许通过扩展方法的形式调用Enroll,进行可以用构造函数直接添加对象。
示例:
public static class StudentExtensions
{
public static void Add(this Enrollment e, Student s) => e.Enroll(s);
}
然后,就可以通过构造函数来直接绑定对象了。如下:
var classList = new Enrollment()
{
new Student("Lessie", "Crosby"),
new Student("Vicki", "Petty"),
new Student("Ofelia", "Hobbs"),
new Student("Leah", "Kinney"),
new Student("Alton", "Stoker"),
new Student("Luella", "Ferrell"),
new Student("Marcy", "Riggs"),
new Student("Ida", "Bean"),
new Student("Ollie", "Cottle"),
new Student("Tommy", "Broadnax"),
new Student("Jody", "Yates"),
new Student("Marguerite", "Dawson"),
new Student("Francisca", "Barnett"),
new Student("Arlene", "Velasquez"),
new Student("Jodi", "Green"),
new Student("Fran", "Mosley"),
new Student("Taylor", "Nesmith"),
new Student("Ernesto", "Greathouse"),
new Student("Margret", "Albert"),
new Student("Pansy", "House"),
new Student("Sharon", "Byrd"),
new Student("Keith", "Roldan"),
new Student("Martha", "Miranda"),
new Student("Kari", "Campos"),
new Student("Muriel", "Middleton"),
new Student("Georgette", "Jarvis"),
new Student("Pam", "Boyle"),
new Student("Deena", "Travis"),
new Student("Cary", "Totten"),
new Student("Althea", "Goodwin")
};
- Improved overload resolution
针对Task.Run()进行了优化,之前版本不能正确的区分重载Task.Run(Action)和Task.Run(Func<Task>())
当以下场景时:
static Task DoThings()
{
return Task.FromResult(0);
}
之前版本,只能写成:
Task.Run(() => DoThings());
6.0就可以正确的写成:
Task.Run(DoThings);
参考:https://docs.microsoft.com/zh-cn/dotnet/articles/csharp/whats-new/csharp-6
回顾C#各版本特性的更多相关文章
- Java14版本特性【一文了解】
「MoreThanJava」 宣扬的是 「学习,不止 CODE」,本系列 Java 基础教程是自己在结合各方面的知识之后,对 Java 基础的一个总回顾,旨在 「帮助新朋友快速高质量的学习」. 当然 ...
- Android各版本特性
此篇文章可以利用碎片化时间进行消化和了解,针对Android各个版本特性,并没有把所有列出,只是抽出了比较常用重要的特性作为提示,同时在面试中只要牢记重要的几个点即可,其他特性直接查找官方文档即可. ...
- 为什么说JAVA中要慎重使用继承 C# 语言历史版本特性(C# 1.0到C# 8.0汇总) SQL Server事务 事务日志 SQL Server 锁详解 软件架构之 23种设计模式 Oracle与Sqlserver:Order by NULL值介绍 asp.net MVC漏油配置总结
为什么说JAVA中要慎重使用继承 这篇文章的主题并非鼓励不使用继承,而是仅从使用继承带来的问题出发,讨论继承机制不太好的地方,从而在使用时慎重选择,避开可能遇到的坑. JAVA中使用到继承就会有两 ...
- C# 语言历史版本特性(C# 1.0到C# 7.1汇总更新) C#各版本新特性 C#版本和.NET版本以及VS版本的对应关系
C# 语言历史版本特性(C# 1.0到C# 7.1汇总更新) 2017年08月06日 11:53:13 阅读数:6705 历史版本 C#作为微软2000年以后.NET平台开发的当家语言,发展至今具有1 ...
- [转帖]sql server版本特性简介、版本介绍简介
sql server版本特性简介.版本介绍简介 https://www.cnblogs.com/gered/p/10986240.html 目录 1.1.sql server的版本信息 1.2.版本重 ...
- Python 如何移除旧的版本特性,如何迎接新的特性?
2020 年 4 月 20 日,Python 2 的最后一个版本 2.7.18 发布了,这意味着 Python 2 是真正的 EOL(end of life)了,一个时代终于落幕了. Python 2 ...
- 全网最通透的Java8版本特性讲解
「MoreThanJava」 宣扬的是 「学习,不止 CODE」,本系列 Java 基础教程是自己在结合各方面的知识之后,对 Java 基础的一个总回顾,旨在 「帮助新朋友快速高质量的学习」. 当然 ...
- 一篇文章看懂spark 1.3+各版本特性
Spark 1.6.x的新特性Spark-1.6是Spark-2.0之前的最后一个版本.主要是三个大方面的改进:性能提升,新的 Dataset API 和数据科学功能的扩展.这是社区开发非常重要的一个 ...
- php不同版本特性记录
最近在用php开发时项目中遇到了版本问题,特此记录下php不同版本的一些特性记录,以备忘. 一:php5.3中的新特性 1)开始支持命名空间(Namespace) 2)支持延迟静态绑定(Late St ...
随机推荐
- phpStudy8.1.0.1配置子域名多网站
版本 这里phpStudy版本为8.1.0.1: 步骤 假设域名为:domain.com:公网IP地址为:42.33.33.33 首先云解析中配置,添加子域名A记录直接指向你的公网IP: ep.dom ...
- Spring Boot第四弹,一文教你如何无感知切换日志框架?
持续原创输出,点击上方蓝字关注我吧 目录 前言 Spring Boot 版本 什么是日志门面? 如何做到无感知切换? 如何切换? 引入依赖 指定配置文件 日志如何配置? 总结 前言 首先要感谢一下读者 ...
- Optimisation
https://www.cnblogs.com/wuyudong/p/writing-efficient-c-and-code-optimization.html 1 不要过多使用 stack ,尽量 ...
- [论文理解] Good Semi-supervised Learning That Requires a Bad GAN
Good Semi-supervised Learning That Requires a Bad GAN 恢复博客更新,最近没那么忙了,记录一下学习. Intro 本文是一篇稍微偏理论的半监督学习的 ...
- 【题解】CF1290B Irreducible Anagrams
Link 题目大意:对于一个字符串,每次询问一个区间,看看这个区间是不是可以划分为若干区间,这些区间内数字经过排列后可以还原原来区间. \(\text{Solution:}\) 菜鸡笔者字符串构造该好 ...
- 浅谈Exgcd(扩展欧几里得)
我们已知,求最大公约数的方法: 求A,B两数的最大公约数,递归求解,递归边界是B==0. gcd(a,b)=gcd(b,a%b) 我们进一步来求Ax+By=Gcd(A,B)的解. 尝试套用欧几里得求法 ...
- Jetson AGX Xavier/ubuntu查找文件
用以下命令查找文件 sudo updatedb locate xxx #xxx是文件名 如果找不到命令,则需要安装mlocate sudo apt-get install mlocate
- JVM初步入门(很初级,建议只做大致了解用)
jvm初步入门 本博客中的所有内容都是来自b站狂神说视频教程,如有侵权联系我删除. 下面是视频链接:b站狂神说 关于jvm的几个小问题 1. jvm的位置: jvm是一个运行在操作系统上的用c语言编写 ...
- 加快ASP。NET Core WEB API应用程序。第2部分
下载source from GitHub 使用各种方法来增加ASP.NET Core WEB API应用程序的生产力 介绍 第1部分.创建测试RESTful WEB API应用程序第2部分.增加了AS ...
- 部署MongoDB-4.2.7
二进制部署很简单 创建存放软件目录下载解压 存放数据和日志及配置文件路径需要手工进行创建 mkdir -p /application/tools/ cd /application/tools/ wge ...