Const和Readonly

2018-09-30  本文已影响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

上一篇 下一篇

猜你喜欢

热点阅读