C# 10.0 和 .NET 6 新特性全解析
1. 初始化只读属性(Init-only Properties)
初始化只读属性允许我们在使用不可变字段时运用对象初始化器。以下是一个 Book 类的示例:
namespace CH01_Books
{
internal class Book
{
public string Title { get; init; }
public string Author { get; init; }
}
}
在 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!");
在这个示例中, Title 和 Author 属性在对象创建时被初始化,之后就不能再修改,这使得 Book 类型是不可变的。
超级会员免费看
订阅专栏 解锁全文
1万+

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



