字段修饰符:readonly 与 const#
来源:
D:\study\C#1\stu0725\stu0725及3题目一:只读字段与常量
const(常量)#
- 在编译时确定值,使用
const声明 - 必须在声明时初始化,之后不能修改
- 默认是
static的,通过类名.常量名访问 - 适用于值不会变化的数据(如税率、税率、配置值)
readonly(只读字段)#
- 在运行时确定值,使用
readonly声明 - 可以在声明时或构造函数中初始化,之后不能修改
- 每个实例可以有不同的值
- 适用于运行时才确定但之后不变的数据(如产品编号、车牌号)
对比#
| 特性 | const |
readonly |
|---|---|---|
| 赋值时机 | 编译时(声明时) | 运行时(声明时或构造函数中) |
| 是否必须声明时初始化 | ✅ 是 | ❌ 否(可在构造函数中初始化) |
| 是否为 static | 是(隐式) | 否(实例级别) |
| 适用场景 | 全局固定值 | 实例创建时确定的值 |
示例 1:Product 类#
class Product
{
public const decimal TaxRate = 0.13m; // 常量:税率
public readonly int ProductId; // 只读:产品编号
public string Name { get; set; }
public decimal Price { get; set; }
public Product(int id, string name, decimal price)
{
ProductId = id; // 构造函数中初始化 readonly 字段
Name = name;
Price = price;
}
public decimal GetTaxAmount()
{
return Price * Product.TaxRate; // const 通过类名访问
}
}
使用:
Product p = new Product(1001, "手机", 2999m);
Console.WriteLine(p.GetTaxAmount()); // 输出 389.87(2999 × 0.13)
// p.ProductId = 1002; // ⚠️ 编译错误:只读字段不能赋值
// Product.TaxRate = 0.15m; // ⚠️ 编译错误:常量不能修改
示例 2:Student 类#
class Student
{
public const string SchoolName = "阳光中学"; // 常量:全校通用
public readonly int StudentId; // 只读:每个学生不同
public string Name { get; set; }
public int Age { get; set; }
public Student(int id, string name, int age)
{
StudentId = id;
Name = name;
Age = age;
}
public void ShowInfo()
{
Console.WriteLine(
$"====学生信息====\n学校:{SchoolName}\n姓名:{Name}\n学号:{StudentId}\n年龄:{Age}");
}
}
使用:
Student s1 = new Student(1, "小明", 18);
Student s2 = new Student(2, "小红", 17);
s1.ShowInfo();
s2.ShowInfo();
// 输出:
// ====学生信息====
// 学校:阳光中学 ← const 常量,所有学生共享
// 姓名:小明
// 学号:1 ← readonly 只读,每个学生不同
// 年龄:18
// ====学生信息====
// 学校:阳光中学
// 姓名:小红
// 学号:2
// 年龄:17
相关笔记#
- 图书管理系统综合练习 — readonly/const 应用
- 静态成员 — 静态成员
- 类与对象基础 — 字段与属性