C#8 语法特性


theme: smartblue

一、 接口方法

在 接口 中支持方法实现 ``` internal interface IStudent { public int GetAge();

public string GetName()
    {
        return "xyy";
    }

}

```

二、 switch 增强

2.1 switch 模式

原用法

```

// 枚举类 internal enum Color { red, green, blue }

// switch 判断 string GetColor(Color color) { switch (color) { case Color.red: return "Red"; case Color.green: return "Green"; case Color.blue: return "Blue"; default: throw new ArgumentException(); }

```

修改后

``` string GetColor(Color color) => color switch { Color.red => "Red", Color.green => "Greem", Color.blue =>"Blue", _ => throw new ArgumentException() };

```

2.2 属性模式

``` internal class Address { public string? State { get; set; } }

decimal GetSaleTax(Address location, decimal salePrice) => location switch { { State:"WA"} => salePrice * 0.06M, { State: "MN" } => salePrice * 0.075M, { State: "MI" } => salePrice * 0.05M, _ => 0 }; ```

2.3 元组模式

string GetWithTuple(string first, string second) => (first, second) switch { ("a", "b") => "the value is a and b", ("c", "d") => "the value is c and d", (_, _) => "fail" };

2.4 位置模式

``` public class Point { public int x { get; set; }

public int y { get; set; }

public Point(int x, int y)
{
    this.x = x;
    this.y = y;
}

public void Deconstruct(out int x, out int y) {
    x = this.x;
    y = this.y;
}

}

int GetPosition(Point point) => point switch { (0 ,0) => 0, var (x,y) when x>0 & y>0 => 1, var (x, y) when x < 0 & y > 0 => 2, var (x, y) when x > 0 & y < 0 => 3, var (_, _)=> 4 };

```

三、 Using 申明

3.1 原用法

void WriteLineToFile() { using (var file=new System.IO.StreamWriter("demo.txt")) { // xxx } }

3.2 现用法

``` void WriteLineToFileNew() { using var file = new System.IO.StreamWriter("demo.txt");

// xxxx

} ```

四、 静态本地函数

方法内可以嵌套方法,并且可以使用 static 关键字 ``` M();

static int M() { int x = 1; int y = 2; return Add( x,y);

static int Add(int x,int y) => x + y;

} ```

五、 异步流

5.1 原代码

``` foreach (int i in ProduceEvenNumbers(9)) { Console.Write(i); Console.Write(" "); } // Output: 0 2 4 6 8

IEnumerable ProduceEvenNumbers(int upto) { for (int i = 0; i <= upto; i += 2) { Thread.Sleep(500); yield return i; } } ```

5.2 异步版本

``` await foreach (int i in ProduceEvenNumbers(9)) { Console.Write(i); Console.Write(" "); } // Output: 0 2 4 6 8

async IAsyncEnumerable ProduceEvenNumbers(int upto) { for (int i = 0; i <= upto; i += 2) { await Task.Delay(500); yield return i; } } ```

六、 索引和范围

C# 索引和范围 - 掘金 (juejin.cn)

七、 null 合并赋值

??= 的作用是当对象值为空时,就允许赋值

``` List number = null; int? i = null;

number ??= new List ();

// i 为 null, 允许赋值 number.Add(i ??= 1);

// i 不为 null, 不允许赋值 number.Add(i ??= 2);

Console.WriteLine(String.Join(" ",number));

```

运行结果

1 1

  • 20
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值