一直用c#开发程序,.net的功能越来越多,变化也挺大的,从最初的封闭,到现在的开源,功能不断的增加,一直在进步。作为c#的强烈支持者,c#的变化,我不能不关注,这篇文章主要介绍,c#6.0和c#7.0增加的功能。c#的发展史和.net以前的版本,请看c#和.net版本,这边文章中有介绍。

c# 6.0版

1. 静态导入

using static 增强功能可用于导入单个类的静态方法。
例如:using static system.string;可以直接用string类中的静态方法,而不用string.xxxx

2. 异常筛选器

“异常筛选器”是确定何时执行catch中的程序, 如果用于异常筛选器的表达式计算结果为 true,则 catch 子句将对异常执行正常处理,如果表达式计算结果为 false,则将跳过 catch 子句。
例如:e.message.contains(“test”)为true执行,否则不执行

try {
    throw new exception("test");
} catch (exception e) when (e.message.contains("test")) {
    console.writeline("ce");
}

3. 只读自动属性、自动属性初始化表达式、expression bodied 成员、字符串内插

可以让属性初始化,仅仅初始化一次,这适用于方法和只读属性
例如:

public class class6
{
    public string lastname { get; set; }
    public string firstname { get; set; }
    public string fullname => $"{firstname} {lastname}";

    public override string tostring() => $"{firstname},{lastname}";
}
//调用
class6 test = new class6();
test.lastname = "jie";
test.firstname = "hua";
console.writeline($"fullname:{test.fullname}, tostring:{test.tostring()}");
test.lastname = "xiao jie";
console.writeline($"fullname:{test.fullname}, tostring:{test.tostring()}");
//运行结果
//fullname:hua jie, tostring:hua,jie
//fullname:hua xiao jie, tostring:hua,xiao jie

4. null 传播器

null 条件运算符使 null 检查更轻松、更流畅。 将成员访问 . 替换为 ?.
例如:var first = person?.firstname; string test = null;string t = test?.tostring();
如果 person 对象是 null,则将变量 first 赋值为 null,否则,将 firstname 属性的值分配给该变量。【?.】的左侧使用任何表达式(包括方法调用)

5. nameof 运算符

nameof 表达式的计算结果为符号的名称,简单来说就是为了显示名称。
例如: string test = “测试”; console.writeline($”{test} , nameof:{nameof(test)}”);
结果:测试 , nameof:test

6. 索引初始值设定项

索引初始值设定项就是对索引初始化,可以像cat cat = new cat { age = 10, name = “fluffy” };初始化值一样,只不过现在增加了索引的初始化

7. catch 和 finally 块中的 await

c# 5 对于可放置 await 表达式的位置有若干限制。 使用 c# 6,现在可以在 catch 或 finally 表达式中使用 await。
例如:

try
{
    throw new exception("test");
}
catch (exception e) when (e.message.contains("test"))
{
    await task.run(() => { console.writeline($"await catch"); });
}
finally
{
    await task.run(() => { console.writeline($"await finally"); });
}

c#7.0

1. out 变量

现在可以在方法调用的参数列表中声明 out 变量,而不是编写单独的声明语句
例如:

if (int.tryparse("123", out int result))
    console.writeline(result)

2. 元组

需要包含多个数据元素的简单结构的方法,也不知道怎么解释,总之就是好用。
例如:

(string name, int age) user = ("小红", 18);
console.writeline($"name:{user.name}, age:{user.age}");
valuetuple<string, int> valuetuple = new valuetuple<string, int>("小红", 18);
//可以和tuple对比学习
tuple<string, int> test = new tuple<string, int>("小红", 18);
//valuetuple是值类型,tuple是引用类型

3. 模式匹配

模式匹配 是一种可让你对除对象类型以外的属性实现方法分派的功能,模式匹配支持 is 表达式和 switch 表达式。每个表达式都允许检查对象及其属性以确定该对象是否满足所寻求的模式,使用 when 关键字来指定模式的其他规则。is 表达式的增强功能, 可以针对值类型和引用类型进行测试。简单来说就是帮你测试类型。
例如:

string test = "123";
if (test is int count) console.writeline(count);

上面的例子会提示int类型的模式无法处理string类型的表达式。

4. 本地函数

许多类的设计都包括仅从一个位置调用的方法。 这些额外的私有方法使每个方法保持小且集中。 本地函数使你能够在另一个方法的上下文内声明方法 。 本地函数使得类的阅读者更容易看到本地方法仅从声明它的上下文中调用。简单来说就是方法中写方法。
例如:

public static int test()
{
    int count = add(12, 10);
    return count;

    int add(int a, int b)
    {
        return a + b;
    }
}

5. ref 局部变量和返回结果

此功能允许使用并返回对变量的引用的算法,这些变量在其他位置定义。
例如:

class numberstore
{
    int[] numbers = { 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023 };

    public ref int findnumber(int target)
    {
        for (int ctr = 0; ctr < numbers.length; ctr++)
        {
            if (numbers[ctr] >= target)
                return ref numbers[ctr];
        }
        return ref numbers[0];
    }

    public override string tostring() => string.join(" ", numbers);
}
var store = new numberstore();
console.writeline($"original sequence: {store.tostring()}");
int number = 16;
ref var value = ref store.findnumber(number);
value *= 2;
console.writeline($"new sequence:      {store.tostring()}");
// the example displays the following output:
//       original sequence: 1 3 7 15 31 63 127 255 511 1023
//       new sequence:      1 3 7 15 62 63 127 255 511 1023

31变成62了,对象中的数组值改变了,这个功能觉得要慎用。

6. 弃元

通常,在进行元组解构或使用 out 参数调用方法时,必须定义一个其值无关紧要且你不打算使用的变量。 为处理此情况,c# 增添了对弃元的支持 。 弃元是一个名为 _(下划线字符)的只写变量,可向单个变量赋予要放弃的所有值。 弃元类似于未赋值的变量;不可在代码中使用弃元(赋值语句除外)。简单来说就是放弃不需要的值。
例如:

private static (string, double, int) test(string name)
{
    return (name, 1.234, 20);
}
//使用
var (name, _, age) = test("测试");
console.writeline($"测试弃元: name:{name}, age:{age}");
//运行结果:测试弃元: name:测试, age:20

7. 二进制文本和数字分隔符

误读的数值常量可能使第一次阅读代码时更难理解。 位掩码或其他符号值容易产生误解。 c# 7.0 包括两项新功能,可用于以最可读的方式写入数字来用于预期用途:二进制文本和数字分隔符 。简单来说就是可以把数字分割等
例如:

int test = 1_123_21;
console.writeline(test);
//结果 112321

8. 引发表达式

throw 始终是一个语句。 因为 throw 是一个语句而非表达式,所以在某些 c# 构造中无法使用它。
例如:string test = false ? “” : throw new exception(“必须是字符串,否则报错。”);

9. 增加异步返回类型valuetask

异步方法返回类型不限于 task、task<t> 和 void,可以是valuetask<int>,可避免在性能上分配 task。
可以查看 【c#中await/async闲说】,这篇文章对异步性能进行了说明,对valuetask的使用进行了说明