zoukankan      html  css  js  c++  java
  • Const与static readonly的区别

    在开发过程中,经常用到Const和static readonly,这两个用法很像,一直以来没有彻底的去了解这两个,今天来做个总结

    本质区别:

      Const是在编译期间确定的,只能在申明时,通过常量赋值。

      static readonly是在运行时确定的,可以通过构造函数来赋值。

    1     public class MyClass
    2     {
    3         public static readonly string Name = "Maple";
    4         public const string Address = "HuBeiWuHan";
    5 
    6         public static readonly MyClass classTest = new MyClass();
    7         public const MyClass classTest1 = new MyClass();
    8     }

    上面代码中第八行编译报错。报错信息:A const field of a reference type other than string can only be initialized with null

    再举一个很明显的例子:

        public class MyClass1
        {
            public static readonly DateTime now = DateTime.Now;  //编译通过
            public const DateTime nowTime = DateTime.Now;    //编译出错 :'System.DateTime' cannot be declared const
        }

    所以,针对const,必须给一个确定的值。 而static readonly,可以在运行期间,对其初始化。

  • 相关阅读:
    202011.19
    202011.18
    202011.17
    202011.16
    202011.14
    jdk的下载和配置
    layui中form表单
    JS中utocomplete
    转:JqueryUI学习笔记-自动完成autocomplete
    JSON.parse()与JSON.stringify()的区别
  • 原文地址:https://www.cnblogs.com/MapleJuan/p/3552877.html
Copyright © 2011-2022 走看看