C# 9 特性一

介绍

接下来我将给大家重点介绍一下.Net 6 之后的一些新的变更,文章都是来自于外国大佬的文章,我这边进行一个翻译,并加上一些自己的理解和解释。

源作者链接:https://blog.okyrylchuk.dev/a-comprehensive-overview-of-c-9-features

正文

目标类型的新表达式

以前在 C# 中,新表达式始终需要指定类型(隐式类型数组表达式除外)。从 C# 9 开始,如果显式定义分配给的类型,则可以删除指定类型。

Person person = new();

目标类型的条件

编译器无法确定条件运算符中分支之间的共享类型?:。如果有目标类型,C# 9 允许它。

class Program
{
     class Person { }
     class Student : Person { }
     class Customer : Person { }

     static void Main(string[] args)
     {
         Student student = new ();
         Customer customer = new ();
         bool isStudent = true;

         // Target-typed conditional ?:. Didn't work in previous C# versions.
         Person person = isStudent ? student : customer;
     }
}

初始化设置器

C# 9 引入了一个新的init访问器来使属性不可变,您可以将它们与对象初始化器一起使用。

class Program
{
    class Person
    {
        public string FirstName { get; init; }
        public string LastName { get; init; }
    }
    static void Main(string[] args)
    {
        var person = new Person()
        {
            FirstName = "Oleg",
            LastName = "Kyrylchuk"
        };
        person.FirstName = "New first name"; // immutable
        person.LastName = "New last name";   // immutable
    }
}

Covariant Returns

在 C# 的派生类中类,无法在方法覆盖中设置更具体的返回型。C# 9 使协变返回成为可能。

class Program
{
    abstract class Cloneable
    {
        public abstract Cloneable Clone();
    }
    class Person : Cloneable
    {
        public string Name { get; set; }
        public override Person Clone()
        {
            return new Person { Name = Name };
        }
        static void Main(string[] args)
        {
            Person person = new Person { Name = "Oleg" };
            Person clonedPerson = person.Clone();
        }
    }
}

顶级项目

C# 9 引入了对初学者友好的顶级程序,没有样板代码:

  • 允许任何陈述
  • 可以等待事情
  • 魔术 args 参数
  • 可以返回状态
using System;
using System.Threading.Tasks;

Console.WriteLine(args);
await Task.Delay(1000);
return 0;

类型模式匹配

C# 9 中改进了模式匹配。
允许将类型作为模式。

static void MatchPatternByType(object o1, object o2)
{
    var tuple = (o1, o2);
    if (tuple is (int, string))
    {
        Console.WriteLine("Pattern matched in if!");
    }
    // OR
    switch (tuple)
    {
        case (int, string):
            Console.WriteLine("Pattern matched in switch!");
            break;
    }
}

关系模式允许在与常数值比较时检查关系约束。

static string GetCalendarSeason(int month) => month switch
{
    >= 3 and < 6 => "spring",
    >= 6 and < 9 => "summer",
    >= 9 and < 12 => "autumn",
    12 or (>= 1 and < 3) => "winter",
    _ => throw new ArgumentOutOfRangeException(nameof(month),
                    $"Unexpected month: {month}."),
};

C# 9 引入了模式组合器来创建逻辑模式:and, or, not.

class Person { 
static void Main()
{
    MatchPatternByType(1, "test")
    // Example with 'not'
    Person person = null;
    if (person is not null) { }

    // Example with 'or' and 'and'
    bool IsLetter(char c) =>
        c is >= 'a' and <= 'z' or >= 'A' and <= 'Z';
}

结语

联系作者:加群:867095512 @MrChuJiu

公众号

posted @ 2022-02-15 14:23  初久的私房菜  阅读(333)  评论(0编辑  收藏  举报
作者:初久的私房菜
好好学习,天天向上
返回顶部小火箭
好友榜:
如果愿意,把你的博客地址放这里
张弛:https://blog.zhangchi.fun/