zoukankan      html  css  js  c++  java
  • const VS readonly in detail

      We know both const and readonly can be used to define unchangeable variables,but what is the difference between'em since they are so similar to each other?

      There are a few points below:

      1.const variables must have a certain value in the compilation time, but for readonly variables, its value can be assigned in run time, for example,
    we can define a readonly variable and assign its value by this way:

        class foo
        {
            public readonly int a;
            public foo()
            {
                a = 10;
            }
        }
    
        or maybe this:
    
        class foo
        {
            public static readonly int a;
            static foo()
            {
                a = 10;
            }
        }

    As we can see, we can assign value to a readonly variable in the constructor,but you won't do this to a const variable.
    BTW: a class may have a static constructor, check it out on google

      2.basically, "const" is just simply a shortcut for "find & replace" when our code is being compiled.Think about this: we have two assamblies say ass1 and ass2, and there is a public const variable,for example "public const int a=10" in some class of ass1 while this const variable is used in another class of ass2. At first we compile these two assamblies and run it, we got the value of the const variable  and that certainly is 10. But now we change the value into 100, and recompile the ass1,guess what we got for the value of the const variable “a” ? 100? No,it's still 10. Why? Because the const variable "a" is replaced into "10" by "find & replace" when the ass2 being compiled, hence, if you don't recompile it, it will keep the value of "10" forever no matter the variable is changed or not in the ass1 where it is defined.
      But this situation won't happend to readonly variables, because the value of readonly variables "is settled down in run time" and it's not "find & replace", it's always referenced by ass2, so the ass2 can always get the newest value as soon as it changed in ass1.

      3.const variables are implicitly static and we can not put the keyword "static" on them, but readonly variables can be done so.We can use "ClassName.ConstName" notation to use public const variables in a class just like readonly variables which are static,if a readonly variable is NOT static, we can only use it by the instance of the class owning it.

  • 相关阅读:
    深入字节码 -- 计算方法执行时间
    RubyCritic:一款不错的检测代码质量工具
    云告警平台 OneAlert :如何帮助运维工程师做好汇报?
    企业应用程序安全的新「守护神」
    另辟蹊径:云计算给企业带来的4个好处
    年度十佳 DevOps 博客文章(后篇)
    自定义 Lint 规则简介
    静态分析安全测试(SAST)优缺点探析
    css添加了原始滚动条要隐藏滚动条的显示
    jquery实现图片切换
  • 原文地址:https://www.cnblogs.com/lwhkdash/p/2973609.html
Copyright © 2011-2022 走看看