C# 9.0 新特性

Record

1、record类型是引用类型
2、为什么会新增这一类型?
    1)面向对象编程中,比较两对象是否相等,一般比较两对象的内存地址是否一致。
    2)然而在一些语境中,我们关注的是对象的字段/属性是否相等。在这种情况下进行比较则需要将对象内的所有字段/属性的值依次进行比较,若全部相等则表示两对象相等,否则不相等。为了简化该语境下的比较,微软新增了record类型,此时可以直接进行比较。

    public class Cat{
        public string NickName { get; set; }
        public int Age { get; set; }
    }

    public record Dog{
        public string NickName { get; set; }
        public int Age { get; set; }
    }

    var cat1 = new Cat{ NickName="二愣子", Age=1 };
    var cat2 = new Cat{ NickName="二愣子", Age=1 };
    Console.WriteLine(cat1 != cat2);

    var dog1 = new Dog{ NickName="二狗子", Age=2 };
    var dog2 = new Dog{ NickName="二狗子", Age=2 };
    Console.WriteLine(dog1 == dog2); 

模式匹配

演变1:
    int score = 99;
	switch(score){
        case 10:
            Console.WriteLine("丢人了!!!");
            break;
        case 60:
            Console.WriteLine("勉强合格!");
            break;
        case 99:
            Console.WriteLine("上帝眷顾!");
            break;
    }

演变2:
    int score = 99;
    switch (score)
    {
        case 0:
            Console.WriteLine("缺考?");
            break;
        case > 0 and <= 30:
            Console.WriteLine("太烂了");
            break;
        case > 30 and < 60:
            Console.WriteLine("还是不行");
            break;
        case >= 60 and < 80:
            Console.WriteLine("还得努力");
            break;
        case >= 80 and < 90:
            Console.WriteLine("秀儿,真优秀");
            break;
        case >= 90 and <= 100:
            Console.WriteLine("不错,奇迹");
            break;
    }

演变3:
    public class Order{
        public float Qty {get; set;}
        public string Name {get; set;}
    }
	Order od = new Order{ Qty = 1000f, Name = "黄金" };
	switch(od){
        case {  Qty: > 1000f, Name:"黄金" }:
            Console.WriteLine("真贵!!!");
            break;
    }

演变4:
    public class Order{
        public float Qty {get; set;}
        public string Name {get; set;}
    }
	Order od = new Order{ Qty = 1000f, Name = "黄金" };
    var res = od switch {
        { Qty: > 1000f, Name:"黄金"  } => true,
        _ => false
    };

扩展用法:
    object n = 5000000L;
    if(n is long x)
    {
        Console.WriteLine("它是个长整型,存放的值是:{0}", x);
    }

init

init 只用于只读属性的初始化阶段,对于可读可写的属性。

最初我们进行属性初始化
    public class Dog
    {
        public int No { get; } = 0;
        public string Name { get; } = "no name";
        public int Age { get; } = 1;

        public Dog(int no, string name, int age)
        {
            No = no;
            Name = name;
            Age = age;
        }
    }

  => Dog dog = new(1001, "亚亚", 4);

现在
    public class Cat
    {
        public int No { get; init; }
        public string Name { get; init; }
        public int Age { get; init; }
    }

  => Cat cat = new Cat { No = 100, Name = "丫丫", Age = 4 };

只读属性初始化结束后不可赋值,故 dog.No = 1; 或 cat.No = 1;都会报错。
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章