美文网首页
Const和Readonly

Const和Readonly

作者: 三岁能抬头 | 来源:发表于2018-09-30 16:11 被阅读0次

常量

对于readonlyconst来说都是用来标识常量,所以他们有相同点。
比如说在赋值之后的编译中值都是恒定不变的(不能二次赋值)。这也符合他们常量的定义,那接下来就说说赋值之前的区别。

赋值

对于赋值来说const在声明的时候就必须要赋值。而readonly可以先声明再赋值,但是要注意的是赋值只能在构造函数内赋值。

public class Class1
{
  public Class1()
  {
    readonly_int = 0;  //后赋值
  }
  public readonly int readonly_int;  //先声明
  public cont int cont_int = 0;  //声明后就赋值
}

这里很明显的看出const是真常量,而readonly是对象被实例化赋值后的常量。

级别

public class Class1{
  public static readonly int static_readonly_int =0;
  public readonly int readonly_int =0;
  public const int const_int =0;
  public static const int const_int =0;  //不可行
}

可见const属于类级别class level的,而不是实例对象级别。简单的说就是static修饰后取值的不同

修饰对象

这里顺便提一句能被const修饰声明为常量的类型必须是以下的基元类型primitive typesbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, float, bool, decimal, string
值得注意的是在上面的类型中除了string以外都是非引用类型,而引用类型是不能被声明为const常量的。
而string虽然是引用类型但是.NET对它特别处理,使得可以const可以有 stringnull 两种值。

其实const才是常数constant,两者只是统一为常量标识,而readonly准确的来说是 " 只读域 " 。

参考文章

END

  • 如果文章内容能误导大家那真是再好不过了,嘻嘻嘻。
  • 文章内容可能持续变更,修改或添加更多内容,以确保内容的准确性。
  • 文章中大部分观点来自引文的总结,写文章的初衷是为了方便回忆。
  • 更新时间:2018-09-30

相关文章

  • Const和Readonly

    常量 对于readonly和const来说都是用来标识常量,所以他们有相同点。比如说在赋值之后的编译中值都是恒定不...

  • 2018-02-12 Const、readOnly、Stati

    第一组:刘聪 Const、readOnly、Static readOnly Const 定义的是静态常在对象初始...

  • C#基本知识点-Readonly和Const的区别

    目录 什么是静态常量(Const)和动态常量(Readonly) 静态常量(Const)和动态常量(Readonl...

  • readonly与const的区别

    const效率高,但readonly更灵活。 区别如下: const是一个编译期常量, readonly是一个运行...

  • 巧用 readonly与 const

    c# 中的常量有两种,分别是编译期常量和运行期常量。通过名字我们就可以看出来它俩在行为上是不同的。在开发中如果这两...

  • C#:const 和 static readonly 区别

    const 用 const 修饰符声明的成员叫常量,是在编译期初始化并嵌入到客户端程序 static readon...

  • 关键字const/static/extern/typedef/t

    1、const(常量---readonly) 作用: 用于修饰 右边 的基本变量或指针变量; 被修饰的变量只读...

  • C#修饰符readonly和const

    参考: const : https://docs.microsoft.com/zh-cn/dotnet/cshar...

  • C#中const和readonly的区别

    在了解这两个关键字的时候我们先来了解一下静态常量和动态常量。静态常量:是指编译器在编译时候会对常量进行解析,并将常...

  • two is C#

    1.readonly:作用类似于将字段声明为const,一旦值设定就不能改变。const字段的值必须在编译时决定,...

网友评论

      本文标题:Const和Readonly

      本文链接:https://www.haomeiwen.com/subject/tsywoftx.html