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,可以在运行期间,对其初始化。

  • 相关阅读:
    手动安装mysql
    spring boot 配置注入
    IOS-电话拦截
    重新入坑-IntelliJ Maven
    git使用问题
    Intelij U
    iTunes空间不足无法备份iphone的问题
    Centos7最小化安装
    实操笔记
    centos7中端口及服务对应情况(笔记)
  • 原文地址:https://www.cnblogs.com/MapleJuan/p/3552877.html
Copyright © 2011-2022 走看看