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

  • 相关阅读:
    STM32 端口复用配置
    stm32 新建文件记得添加到工程
    keil解决SYSTEMsysstm32f10x.h(298): error: #67: expected a "}"
    解决Keil复制中文乱码
    STM32 MPU6050 源码
    STM32 PWM输出
    STM32定时器
    STM32 看门狗操作姿势
    开课博客
    第二周学习进度
  • 原文地址:https://www.cnblogs.com/MapleJuan/p/3552877.html
Copyright © 2011-2022 走看看