const用于编译时常量,必须在声明时初始化,仅支持基本类型、enum和string,值嵌入调用代码;readonly用于运行时常量,可在声明或构造函数中赋值,支持所有类型,每实例可不同;需运行时计算或复杂类型时用readonly,全局唯一延迟初始化可用static readonly。

const 和 readonly 都可用于定义不可变的值,但它们在使用时机、赋值方式和适用范围上有明显区别。
<font>const int MaxValue = 100; const string Version = "1.0"; const bool IsDebug = true;</font>
<font>public class Config
{
public readonly int Timeout;
public readonly DateTime CreatedTime;
public Config(int timeout)
{
Timeout = timeout;
CreatedTime = DateTime.Now;
}
}</font><font>public static class GlobalConfig
{
public static readonly DateTime LaunchDate = new DateTime(2025, 4, 1);
}</font>以上就是C#的const和readonly有什么区别?如何定义常量?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号