属性与索引器
get/set 访问器、自动属性、init 只读、表达式体成员、索引器 this[]
属性与索引器
C# 的属性封装了 get/set 逻辑——和字段一样使用,但可以加验证、计算、懒加载。
学完本章你将: 掌握 get/set 访问器、自动属性、init 只写、索引器。
自动属性
csharp
public class Person
{
// 自动属性(最常用)
public string Name { get; set; }
// 只读属性
public int Id { get; }
// init 只写(只能在初始化时设置)
public DateTime CreatedAt { get; init; }
// 带默认值
public int Age { get; set; } = 18;
}
var p = new Person { Name = "小明", CreatedAt = DateTime.Now };
// p.CreatedAt = DateTime.Now; // ❌ 错误——init 只读
手动属性
csharp
public class Temperature
{
private double celsius;
public double Celsius
{
get => celsius;
set
{
if (value < -273.15)
throw new ArgumentException("低于绝对零度");
celsius = value;
}
}
// 计算属性
public double Fahrenheit => celsius * 9 / 5 + 32;
}
索引器 —— 像数组一样访问
csharp
public class StringList
{
private readonly List<string> items = new();
// 索引器定义
public string this[int index]
{
get => items[index];
set => items[index] = value;
}
// 多参数索引器
public string this[int row, int col] => /* ... */;
}
var list = new StringList();
list[0] = "Hello";
Console.WriteLine(list[0]); // "Hello"