C#中的readonly(运行时常量)与const(编译时常量)的区别

  今天看了一篇文章,介绍了在《Effictive C#》中对静态变量和动态变量的说明和各自的优缺点。
     

对于在定义常量的时候,到底是用const来定义还是readonly来定义。在此书中,提到了一个关于使用const会产生潜在的bug。就是在程序中使用DLL类库某个类的静态常量时,如果在类库中修改静态常量的值,其它接口没有发生变化,一般来说,程序调用端是不需要重新编译,直接执行就可以调用新的类库。不过就是在此情况下,会产生潜在的bug。这是由于静态常量在编译的时候,是用它的值去替换常量,因此在调用端的程序也是这样进行替换的。

例如:在类库中定义了一个静态常量,如下:

public const int MAX_VALUE = 10;

那么对于程序中调用此静态常量这段代码,在编译后产生的中间语言代码中,是用10来进行替换,即使用静态常量的地方,改为10了。

那么当类库的静态变量发生变化后,例如:

public const int MAX_VALUE = 15;

那么对于调用端程序是可以在没有重新编译的情况下进行运行,不过此时程序的中间语言代码对应于静态变量的值是10,而不是新类库中的15。因此这样产生的不一致,程序会引发潜在的bug。解决此类问题的方法,就是调用端程序在更新类库之后重新编译一下,即生成新的中间语言代码。

现在将就这两种类型的不同特性进行比较并说明各自的适用场景:

工作原理
    readonly为运行时常量,程序运行时进行赋值,一旦赋值便无法更改,因此也有人称其为只读变量。
    const为编译时常量,程序编译时将对常量值进行解析,并将所有常量引用替换为相应值。
    下面声明两个常量:


public static readonly int A = 2; //A为运行时常量
public const int B = 3; //B为编译时常量
    注意,const默认为static类型,所以无需用static修饰,如果强制用static进行声明将导致编译错误。
    下面的表达式:

int C = A + B;
    经过编译后与下面的形式等价:

int C = A + 3;
    可以看到,其中的const常量B被替换成字面量3,而readonly常量A则保持引用方式。

数据类型支持
    由于const常量在编译时将被替换为字面量,使得其取值类型受到了一定限制。const常量只能被赋予数字(整数、浮点数)、字符串以及枚举类型。下面的代码无法通过编译:


public const DateTime D = DateTime.MinValue;
    改成readonly就可以正常编译:

public readonly DateTime D = DateTime.MinValue;

可维护性
    readonly以引用方式进行工作,某个常量更新后,所有引用该常量的地方均能得到更新后的值。
    const的情况要稍稍复杂些,特别是跨程序集调用:


public class Class1
{
    public static readonly int A = 2; //A为运行时常量
    public const int B = 3; //B为编译时常量
}

public class Class2
{
    public static int C = Class1.A + Class1.B; //变量C的值为A、B之和
}

Console.WriteLine(Class2.C); //输出"5"
    假设Class1与Class2位于两个不同的程序集,现在更改Class1中的常量值:

public class Class1
{
    public static readonly int A = 4; //A为运行时常量
    public const int B = 5; //B为编译时常量
}
    编译Class1并部署(注意:这时并没有重新编译Class2),再次查看变量C的值:

Console.WriteLine(Class2.C); //输出"7"
    结果可能有点出乎意料,让我们来仔细观察变量C的赋值表达式:

public static int C = Class1.A + Class1.B;
    编译后与下面的形式等价:

public static int C = Class1.A + 3;
    因此不管常量B的值如何变,对最终结果都不会产生影响。虽说重新编译Class2即可解决这个问题,但至少让我们看到了const可能带来的维护问题。

性能比较
    const直接以字面量形式参与运算,性能要略高于readonly,但对于一般应用而言,这种性能上的差别可以说是微乎其微。

适用场景
    在下面两种情况下:
    a.取值永久不变(比如圆周率、一天包含的小时数、地球的半径等)
    b.对程序性能要求非常苛刻
    可以使用const常量,除此之外的其他情况都应该优先采用readonly常量。

Const   静态的常量。

Readonly

final java 一样概念

静态的常量。


常量定义:在编译时。运行时不可以修改。
必须定义成:成员变量。




常量必须是
integral 完整类型type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or string),an enumeration, or a reference to null.



其实就是基本类型 ==java 





Since classes or structures are initialized at run time with the new keyword, and not at compile time, you can't set a constant to a class or structure. 

  
常量 定义后就和 static 静态变量一样用。不需要static 关键字。

Constants are accessed as if they were static fields, although they cannot use the static keyword.

常量可以标记的前缀:
public, private, protected, internal, or protected internal.


Constants can be marked as public, private, protected, internal, or protected internal.

类名.常量


To use a constant outside of the class that it is declared in, you must fully qualify it using the class name.

动静态 都可以。

Class Instance 变量。的属性是可以修改的

Struct 的不是不可以 修改他的属性的。

readonly字段的赋值只能作为字段声明的组成部分出现,或在同一类中的实例构造函数静态构造函数中出现。


一个只读成员,表现出 不可以被修改。
只读成员, 初始化 在运行时。。。

可以初始化 在  定义 或者 构造




public class MyClass             {             public readonly double PI = 3.14159;             }

or

public class MyClass             {             public readonly double PI;                           public MyClass()             {             PI = 3.14159;             }             }

注意
 只读成员  不是 隐式的静态,但是可以用static 修饰。

readonly 关键字 可以用 复杂类型,可以用new 关键子 初始化。


readonly 不能是 enu 枚举类型。

    const string sv = "abc" ;

    const float pii = 3.1415926f;

    const static string psss = "aaa"// 默认就是的static 并且这样不行

const string sss = null;



readonly string rdstr = System.Windows.Forms.Application.StartupPath + "aaa";

   Test() { // 构造函数。

    rdstr = "s" + sv;

    }

    private static readonly string path = System.Windows.Forms.Application.StartupPath + "aaa";

想赋值都不行。 只能用null

    const Test testt = new Test();

Test.cs(122,24): error CS0134:
        “Acme.Collections.Test.testt”的类型为“Acme.Collections.Test”。只能用
        null 对引用类型(字符串除外)的常量进行初始化

        Console.WriteLine( new Test().rdstr);  

        /*

         Test.cs(142,27): error CS0120:

        非静态的字段、方法或属性“Acme.Collections.Test.rdstr”要求对象引用

         */

        Console.WriteLine(path);


原文地址:https://www.cnblogs.com/dudu837/p/1558794.html