C# 10.0 和 .NET 6 新特性介绍
1. 初始化只读属性(Init-Only Properties)
在 C# 10.0 中,初始化只读属性允许我们在使用对象初始化器时操作不可变字段。以一个 Book 类为例:
namespace CH01_Books
{
internal class Book
{
public string Title { get; init; }
public string Author { get; init; }
}
}
这些属性在创建 Book 对象时可以初始化,但一旦创建,就只能读取,不能更新,从而使 Book 类型成为不可变类型。在 Program 类中使用:
using System;
using CH01_Books;
var bookName = new Book { Title = "Made up book name",
Author = "Made Up Author" };
Console.WriteLine($"{bookName.Title} is written by
{bookName.Author}. Well worth reading!");
上述代码导入了 System 和 C
超级会员免费看
订阅专栏 解锁全文
1283

被折叠的 条评论
为什么被折叠?



