C# 8.0 的新特性( NET Framework 4.8 与 Visual Studio 2019 )
C#8.0 于 2019年4月 随 .NET Framework 4.8 与 Visual Studio 2019 一同发布
使用VS2019体检C#8.0新功能:
编辑.csproj文件,添加如下代码
<PropertyGroup>
<LangVersion>preview</LangVersion>
</PropertyGroup>
一、可空引用类型(Nullable reference types)
引用类型将会区分是否可空,可以从根源上解决 NullReferenceException。
#nullable enable
void M(string? s)
{
Console.WriteLine(s.Length); // 产生警告:可能为 null
if (s != null)
{
Console.WriteLine(s.Length); // Ok
}
}
#nullable disable
二、异步流(Async streams)
考虑到大部分 Api 以及函数实现都有了对应的 async版本,而 IEnumerable<T>和 IEnumerator<T>还不能方便的使用 async/await就显得很麻烦了。
但是,现在引入了异步流,这些问题得到了解决。
我们通过新的 IAsyncEnumerable<T>和 IAsyncEnumerator<T>来实现这一点。同时,由于之前 foreach是基于IEnumerable<T>和 IEnumerator<T>实现的,因此引入了新的语法await foreach来扩展 foreach的适用性。
async Task<int> GetBigResultAsync()
{
var result = await GetResultAsync();
if (result > ) return result;
else return -;
} async IAsyncEnumerable<int> GetBigResultsAsync()
{
await foreach (var result in GetResultsAsync())
{
if (result > ) yield return result;
}
}
三、范围和下标类型(Ranges and indices)
C# 8.0 引入了 Index 类型,可用作数组下标,并且使用 ^ 操作符表示倒数。
不过要注意的是,倒数是从 1 开始的。
Index i1 = ; // 下标为 3
Index i2 = ^; // 倒数第 4 个元素
int[] a = { , , , , , , , , , };
Console.WriteLine($"{a[i1]}, {a[i2]}"); // "3, 6"
除此之外,还引入了 “..” 操作符用来表示范围(注意是左闭右开区间)。
var slice = a[i1..i2]; // { 3, 4, 5 }
关于这个下标从 0 开始,倒数从 1 开始,范围左闭右开。
四、模式匹配表达式(Switch expressions )
典型的模式匹配语句,只不过没有用“match”关键字,而是沿用了了“switch”关键字
object figure = "";
var area = figure switch
{
Line _ => ,
Rectangle r => r.Width * r.Height,
Circle c => c.Radius * 2.0 * Math.PI,
_ => throw new UnknownFigureException(figure)
};
C# 8.0中的模式匹配相对C# 7.0来说有了进一步的增强,对于如下类:
class Point
{
public int X { get; }
public int Y { get; }
public Point(int x, int y) => (X, Y) = (x, y);
public void Deconstruct(out int x, out int y) => (x, y) = (X, Y);
}
首先来看C# 7.0中一个经典的模式匹配示例:
static string Display(object o)
{
switch (o)
{
case Point p when p.X == && p.Y == :
return "origin";
case Point p:
return $"({p.X}, {p.Y})";
default:
return "unknown";
}
}
在C# 8.0中,它有更加精简的写法。
1、Switch表达式
在C# 8.0中,可以利用新的switch方式成模式匹配:
static string Display(object o) => o switch
{
Point p when p.X == && p.Y == => "origin",
Point p => $"({p.X}, {p.Y})",
_ => "unknown"
};
它利用一条switch语句完成了模式匹配,第一样看上去要简洁一些。不过,它还有更多更简单的写法。
2、Property patterns
可以直接通过在属性上指定值作为判定条件,
static string Display(object o) => o switch
{
Point { X: , Y: } => "origin",
Point p => $"({p.X}, {p.Y})",
_ => "unknown"
};
也可以将属性值传递出来。
static string Display(object o) => o switch
{
Point { X: , Y: } => "origin",
Point { X: var x, Y: var y } => $"({x}, {y})",
_ => "unknown"
};
3、Positional patterns
利用解构函数,可以写出更加精简的表达式。
static string Display(object o) => o switch
{
Point(, ) => "origin",
Point(var x, var y) => $"({x}, {y})",
_ => "unknown"
};
如果没有类型转换,则可以写得更加简单了:
static string Display(Point o) => o switch
{
(, ) => "origin",
(var x, var y) => $"({x}, {y})"
};
4、非空判断
如果只是判断空和非空,则有最简单的模式:
{ } => o.ToString(),
null => "null"
5、Tuple patterns
也支持直接对ValueTuple进行模式匹配,用起来非常灵活。
static State ChangeState(State current, Transition transition, bool hasKey) =>
(current, transition, hasKey) switch
{
(Opened, Close, _) => Closed,
(Closed, Open, _) => Opened,
(Closed, Lock, true) => Locked,
(Locked, Unlock, true) => Closed,
_ => throw new InvalidOperationException($"Invalid transition")
};
五、递归模式语句(recursive patterns)
现在可以这么写了(patterns 里可以包含 patterns)
IEnumerable<string> GetEnrollees()
{
foreach (var p in People)
{
if (p is Student { Graduated: false, Name: string name }) yield return name;
}
}
C# 8.0 的新特性( NET Framework 4.8 与 Visual Studio 2019 )的更多相关文章
- C# 7.0 中的新特性((.NET Framework 4.7 与 Visual Studio 2017 ))
C#7.0 于 2017年3月 随 .NET 4.7 和 VS2017 发布. 一. out 变量(out variables) 以前我们使用out变量必须在使用前进行声明,C# 7.0 给我们提供了 ...
- C# 8.0 的新特性概览和讲解
本文转自 https://blog.csdn.net/hez2010/article/details/84036742 C# 8.0 的新特性概览和讲解 前言 新的改变 可空引用类型(Nullable ...
- php5.3到php7.0.x新特性介绍
<?php /*php5.3*/ echo '<hr>'; const MYTT = 'aaa'; #print_r(get_defined_constants()); /* 5.4 ...
- paip.php 5.0 5.3 5.4 5.5 -6.0的新特性总结与比较
paip.php 5.0 5.3 5.4 5.5 -6.0的新特性总结与比较 PHP5的新特性 2 · 对象的参照过渡是默认的(default) 3 · 引入访问属性的限制 3 · 引入访问方法的限 ...
- NodeJS 框架 Express 从 3.0升级至4.0的新特性
NodeJS 框架 Express 从 3.0升级至4.0的新特性 [原文地址:√https://scotch.io/bar-talk/expressjs-4-0-new-features-and-u ...
- 相比于python2.6,python3.0的新特性。
这篇文章主要介绍了相比于python2.6,python3.0的新特性.更详细的介绍请参见python3.0的文档. Common Stumbling Blocks 本段简单的列出容易使人出错的变动. ...
- MySQL 8.0 InnoDB新特性
MySQL 8.0 InnoDB新特性 1.数据字典全部采用InnoDB引擎存储,支持DDL原子性.crash safe,metadata管理更完善 2.快速在线加新列(腾讯互娱DBA团队贡献) 3. ...
- Atitit jquery 1.4--v1.11 v1.12 v2.0 3.0 的新特性
Atitit jquery 1.4--v1.11 v1.12 v2.0 3.0 的新特性 1.1. Jquery1.12 jQuery 2.2 和 1.12 新版本发布 - OPEN资讯.h ...
- [PHP] 从PHP 5.6.x 移植到 PHP 7.0.x新特性
从PHP 5.6.x 移植到 PHP 7.0.x 新特性: 1.标量类型声明 字符串(string), 整数 (int), 浮点数 (float), 布尔值 (bool),callable,array ...
随机推荐
- 深度解析qml引擎---(1)Qml文件加载
"美的事物是永恒的喜悦" --- 济慈 ...
- linux-sysbench
sysbench是一个模块化的.跨平台.多线程基准测试工具,主要用于评估测试各种不同系统参数下的数据库负载情况.关于这个项目的详细介绍请看:http://sysbench.sourceforge.ne ...
- [Oracle] - 查看数据库中每个表占用空间大小,及进行表压缩
查询用户创建的表 select * from user_tab_comments; -- 查询本用户的表,视图等. select * from user_col_comments; -- 查询本用户的 ...
- libevent实现TCP 客户端
ibevent实现Tcp Client基于bufferevent实现 #include <stdio.h> #include <unistd.h> #include <s ...
- 从create-react-app开始,构建项目架构
1.生成项目 命令行执行:create-react-app myapp,生成如下结构: 2.安装sass依赖,让你在项目中可以使用scss模块化,index.module.scss: npm i n ...
- golang ---获取IP Address
package main import ( "fmt" "log" "os/exec" "regexp" ) func ...
- 转:深入浅出Java垃圾回收机制
原文链接:http://www.importnew.com/1993.html 对于Java开发人员来说,了解垃圾回收机制(GC)有哪些好处呢?首先可以满足作为一名软件工程师的求知欲,其次,深入了解G ...
- c#中冒泡排序算法描述
int temp = 0; int b = 0; int[] arr = { 23, 44, 66, 76, 98, 11, 3, 99, 7 };# region该段与排序无关Console.Wri ...
- 易百教程人工智能python修正-人工智能监督学习(分类)
分类技术或模型试图从观测值中得出一些结论. 在分类问题中,我们有分类输出,如“黑色”或“白色”或“教学”和“非教学”. 在构建分类模型时,需要有包含数据点和相应标签的训练数据集. 例如,如果想检查图像 ...
- python PIL图像处理库
1. Introduction PIL(Python Image Library)是python的第三方图像处理库,但是由于其强大的功能与众多的使用人数,几乎已经被认为是python官方图像处理库了. ...