what's the differences between readonly & const in C# 在C#中readonly和const的区别

1. the similar feature 相似性
   grammar:
    public const int x=100;
    public readonly int x;    
    const variable and readonly variable can not be modified once they are initialized in run-time. However,the main differences between them is the time to be initialized!
const变量和readonly变量的值一旦被初始化其值在运行时就不能再改变。但是,他们之间的区别在于他们被初始化的时机是不一样的。

2 the differences
    const variable must be initialized when it's be declared, because  its value is set in compile-time before the respective object is constructed. However, readonly can be initialized dynamically. that is to say, its value can be set via class constructor or vairable initiazer(no other feasible ways).
    const常量必须在其声明时被初始化,因为其值在编译而相应对象构造之前就被设定。但是 ,readonly可以被动态设定,其既可以在初始化时设定,也可以在构造函数中设定(其他方式均不可)。
   e.g
    public class A
    {
        public const m_x=100;

        //public const m_x=DataTime.Now.Tricks;
        //error!DataTime.Now.Tricks can not give a exact value for const variable in compile-time.
        public readonly long  m_y=DataTime.Now.Tricks;
        //it can be initialized via viriable initiazer

        public readonly int  m_z;
        public A()
        {
        m_z=DataTime.Now.Tricks;
        //it also can be initialized via constructor;
        }
    }
    

posted on   飞天舞者  阅读(333)  评论(1编辑  收藏  举报

编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构

导航

< 2008年4月 >
30 31 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 1 2 3
4 5 6 7 8 9 10
For more information about me, feel free email to me winston.he@hotmail.com
点击右上角即可分享
微信分享提示