zoukankan      html  css  js  c++  java
  • 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;
            }
        }
        
  • 相关阅读:
    关于几种滤波的对比
    学习笔记深入理解Java中的HashMap数据结构
    学习笔记Redis基础常识
    学习笔记Java内存模型
    学习笔记理解GC
    工作中的点点滴滴单例的使用
    工作中的点点滴滴学习一下门面模式
    工作中的点点滴滴接口幂等的问题
    【转载】WCF、WebAPI、WCFREST、WebService之间的区别
    【转载】工具分享——将C#文档注释生成.chm帮助文档
  • 原文地址:https://www.cnblogs.com/Winston/p/1169427.html
Copyright © 2011-2022 走看看