C#9 语法特性

27 阅读1分钟

一、 Record

1.1 基础用法

internal record Student
{
    public int Id { get; set; } = 24;

    public string Name { get; set; } = "xyy";

}
Person person = new Person("F","L");
Console.WriteLine($"fitst name {person.firstName}, last name {person.lastName}");

// 将 对象属性 赋予到 变量
person.Deconstruct(out string firstName, out string lastName);
Console.WriteLine($"fitst name {firstName}, last name {lastName}");

1.2 不可变性

默认 Record 属性不可变,Person 相当于 Person2 写法,只能在初始化值时设置内容

internal record Person(String firstName,string lastName);

internal record Person2() {
    public string fitstName { get; init; } = default!;
    public string lastName { get; init; } = default!;
};

也可添加 set 允许,属性能够改变

internal record Person3()
{
    public string fitstName { get; set; } = default!;
    public string lastName { get; set; } = default!;
};

1.3 值相等性

若要依次比较两个 Record 对象是否相等,可直接使用 =

Person person1 = new Person("F","L");
Person person2 = new Person("F", "L");
Console.WriteLine(person2 == person1); // true

Person person3 = new Person("L", "F");
Console.WriteLine(person3 == person2); // false

若要比较引用地址是否相等,可使用 ReferenceEquals 方法

Person person1 = new Person("F","L");
Person person2 = new Person("F", "L");
Console.WriteLine(ReferenceEquals(person1,person2)); // false

1.4 非破坏性变换

可以使用 with 关键词修改指定属性

Person person3 = person2 with { firstName="T"};
Console.WriteLine(person2);
Console.WriteLine(person3);

执行结果如下:

Person { firstName = F, lastName = L }
Person { firstName = T, lastName = L }

二、 仅限 Init 的资源库

添加 init 后,仅限于初始化时可以赋值

 internal class Person2() {
     public string fitstName { get; init; } = default!;
     public string lastName { get; init; } = default!;
 };

三、 目标类型的 new 表达式

// 原写法
Student student1 = new Student();
// 修改后
Student student2 = new();

并且传入方法的参数为对象时,也可简写

MyFunc(new());

void MyFunc(Student student){
    
};