C#常量——const和readonly(2)

补充上一篇文章

对于运行时常量,只能在初始化时赋值,或者是构造函数中复制。而不能在其他地方赋值,否则会提示错误。

还是用上篇的例子,在Limitations中我定义了两个常量,但是对运行时常量没有赋值,

public class Limitations
{
public static readonly int startValue ;
public const int endValue=10 ;
}

该类库编译通过,没有问题。

在主程序中调用时,我企图对运行时变量进行赋值,如下

class Program
{
static void Main(string[] args)
{
Limitations.startValue
= 5;//企图对运行时变量进行赋值
for (int i = Limitations.startValue; i < Limitations.endValue; i++)
{
Console.WriteLine(i.ToString());
}
Console.Read();
}
}

 编译时,提示错误如下:

提示我们,对于运行时变量,只能在构造函数和初始化时对其赋值。因为我用的运行时变量时静态的,所以错误提示我在静态构造函数中赋值,这没有冲突。

原文地址:https://www.cnblogs.com/ATually/p/1914602.html