const是编译时常量,值在编译时确定且所有实例共享,适用于如PI等固定值;readonly是运行时常量,可在构造函数中初始化,每个实例可不同,适用于创建时间等需运行时赋值的场景。

readonly
const
const
readonly
readonly
const
C#中的
readonly
const
readonly
const
最核心的区别在于,
const
readonly
const
const
const
const
public const int MaxValue = 100; // 正确,100是编译时常量 // public const int CurrentTime = DateTime.Now.Hour; // 错误,DateTime.Now.Hour的值在运行时才能确定
readonly
readonly
readonly
public readonly DateTime CreationTime;
public MyClass() {
CreationTime = DateTime.Now; // 正确,在构造函数中初始化
}这里,
CreationTime
MyClass
CreationTime
const
const
public const double PI = 3.14159;
public const string AppName = "MyApplication";
public const int DefaultErrorCode = 0;
使用
const
const
readonly
readonly
CreationTime
public readonly ILogger Logger;
public readonly int TotalCount = CalculateTotal();
使用
readonly
const
static readonly
static readonly
public static readonly string AppVersion = GetAppVersion();
private static string GetAppVersion() {
// 从配置文件或数据库中读取版本号
return "1.2.3";
}在这个例子中,
AppVersion
MyClass
readonly
需要注意的是,
readonly
readonly
public readonly List<string> Items = new List<string>();
public void AddItem(string item) {
Items.Add(item); // 这是允许的,因为Items指向的List对象的内容可以改变
}如果想要保证引用类型的内容也不可变,可以使用不可变集合,比如
ImmutableList<string>
选择
const
readonly
const
readonly
以上就是C#的readonly关键字和const有什么区别?何时使用?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号