C#8 语法特性

28 阅读1分钟

一、 接口方法

在 接口 中支持方法实现

    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<int> 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<int> ProduceEvenNumbers(int upto)
{
    for (int i = 0; i <= upto; i += 2)
    {
        await Task.Delay(500);
        yield return i;
    }
}

六、 索引和范围

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

七、 null 合并赋值

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

List<int> number = null;
int? i = null;

number ??= new List<int>();

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

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

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

运行结果

1 1