C# 版本 7.1 新增特性
发布时间:2017 年 8 月
C# 已开始随 C# 7.1 发布_单点发行_。 此版本增加了语言版本选择配置元素、三个新的语言功能和新的编译器行为。
此版本中新增的语言功能包括:
async``Main方法- 应用程序的入口点可以含有
async修饰符。
- 应用程序的入口点可以含有
default文本表达式- 在可以推断目标类型的情况下,可在默认值表达式中使用默认文本表达式。
- 推断元组元素名称
- 在许多情况下,可通过元组初始化来推断元组元素的名称。
- 泛型类型参数的模式匹配
- 可以对类型为泛型类型参数的变量使用模式匹配表达式。
最后,编译器有 -refout 和 -refonly 两个选项,可用于控制引用程序集生成。
参考文章:
C#7.1 新增功能 - 张传宁 - 博客园
笔记
async Main 方法
可以在 Main 方法上标记 async 关键字,并使用 await。
static async Task Main()
{
await SomeAsyncMethod();
}
default 文本表达式
int myInt = default; // 等同于 int myInt = 0;
string myString = default; // 等同于 string myString = null;
bool myBool = default; // 等同于 bool myBool = false;
T myGenericVar = default(T); // 或者更简洁地写作 T myGenericVar = default;
//Func<string, bool> whereClause = default(Func<string, bool>); // 这是旧的写法
推断元组元素名称
右侧赋值的变量名与元组元素名同名,方便使用
int count = 5;
string label = "Colors used in the map";
var pair = (count, label); // element names are "count" and "label"
泛型类型参数的模式匹配
is 和 switch 类型模式的模式表达式的类型可能为泛型类型参数。 这可能在检查 struct 或 class 类型且要避免装箱时最有用。
⭐ 妙❗ 参考文章:模式 - 使用 is 和 switch 表达式进行模式匹配。 - C# reference | Microsoft Learn
// is: 泛型类型的模式匹配
public void Process<T>(T item)
{
if (item is string str)
{
Console.WriteLine("The item is a string: " + str);
}
else if (item is int num)
{
Console.WriteLine("The item is an integer: " + num);
}
else
{
Console.WriteLine("The item is of an unknown type.");
}
}
// c# 8 中的switch模式匹配
public string Describe<T>(T item)
{
return item switch
{
string str => "The item is a string with value: " + str,
int num => "The item is an integer with value: " + num,
_ => "The item is of an unknown type."
};
}
引用程序集生成
有两个新编译器选项可生成仅引用程序集:-refout 和 -refonly 。 链接的文章详细介绍了这些选项和引用程序集。

浙公网安备 33010602011771号