Home  >  Article  >  php教程  >  readonly和const区别(C#)

readonly和const区别(C#)

WBOY
WBOYOriginal
2016-06-06 20:01:202061browse

1. readonly 和 const 都是用来标识常量的。 2. const 可用于修饰 class 的 field 或者一个局部变量( local variable );而 readonly 仅仅用于修饰 class 的 field 。 3. const 常量的值必定在编译时就已明确并且恒定的;而 readonly 常量却有一点不同,那

1.      readonlyconst都是用来标识常量的。

2.      const可用于修饰classfield或者一个局部变量(local variable);而readonly仅仅用于修饰classfield

3.      const常量的值必定在编译时就已明确并且恒定的;而readonly常量却有一点不同,那就是其值可以在运行时编译,当然,它也必须遵守作为常量的约束,那就是值必须恒定不变。

4.      const常量必须在声明的同时对其进行赋值,并且确保该值在编译时可确定并恒定;而readonly常量则可以根据情况选择在声明的同时对其赋予一个编译时确定并恒定的值,或者将其值的初始化工作交给实例构造函数(instant constructor)完成。如:public readonly string m_Now = DateTime.Now.ToString();m_Now会随着运行时实际情况变化而变化。

5.      const常量属于类级别(class level)而不是实例对象级别(instant object level),并且它不能跟static结合一起使用,该常量的值将由整个类的所有实例对象共同分享(详细论述参见后面的Remark区域)。

6.      readonly常量既可以是类级别也可以是实例对象级别的,这取决于它的声明以及初始化工作怎么实施。readonly可以与static结合使用,用于指定该常量属于类级别,并且把初始化工作交由静态构造函数(static constructor)完成(有关如何把readonly常量声明为类级别或实例对象级别的论述清参见后面的Remark区域)

7.      能被const修饰声明为常量的类型必须是以下的基元类型(primitive type):sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, float, bool, decimal, string

8.      object, 数组(Array结构(struct)不能被声明为const常量。

9.      一般情况下,引用类型是不能被声明为const常量的,不过有一个例外:string。该引用类型const常量的值可以有两种情况,stringnull。其实,string虽然是引用类型,但是.NET却对它特别处理,这种处理叫做字符串恒定性(immutable),使得string的值具有只读特性。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:存储过程解密Next article:Hastable 用法及循环读取