• 新特性


    来源:https://mp.weixin.qq.com/s/4uW6z8yvTt89_y9OyK_y5g

    1.record 类型(record 是引用类型,跟 class 很像(确实差不多))

    Cat pet1 = new Cat
    {
        Nick = "松子",
        Name = "Jack",
        Age = 1
    };
    Cat pet2 = new Cat
    {
        Nick = "松子",
        Name = "Jack",
        Age = 1
    };
    // 居然不是同一只猫
    Console.WriteLine("同一只?{0}", pet1 == pet2);

    答案是  否

    换成 ecord   答案就     是

    record 类型让你省去了重写相等比较(重写 Equals、GetHashCode 等方法或重载运算符)的逻辑。

     实际上,代码在编译后 record 类型也是一个类,但自动实现了成员相等比较的逻辑。以前你要手动去折腾的事现在全交给编译器去干。

    2.属性的 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;
        }
    }

    现在:把后面的set  设置为 init; 

    public class Dog
    {
        public int No { get; init; }
        public string Name { get; init; }
        public int Age { get; init; }
    }

    实例化时直接为属性赋值。

    Dog x = new Dog
    {
    No = 100,
    Name = "吉吉",
    Age = 4
    };
  • 相关阅读:
    有一种尺度叫圆融
    十大经典排序算法
    Maximal Square
    Word Break
    Flatten List
    Triangle
    Paint Fence
    Longest Increasing Continuous Subsequence
    Minimum Size Subarray Sum
    Letter Combinations of a Phone Number
  • 原文地址:https://www.cnblogs.com/yyl001/p/14042646.html
Copyright © 2020-2023  润新知