【发布时间】:2013-06-05 13:23:34
【问题描述】:
我的一些全局变量只需要启动一次。我通过加载文件并将它们设置为任何内容来做到这一点。现在我想当我尝试为这个变量设置一个新值时抛出一个异常。
public class Foo
{
public static int MIN;
private static loadConstants()
{
MIN = 18;
}
public static void Main()
{
loadConstants();
MIN = 15; // this must throw an exception
// edit: at least mustn't set the new value
}
}
我该怎么做?
(可能很简单,对不起)
【问题讨论】:
-
"this must throw an exception" -- 你真的需要它来编译,直到运行时才失败?到目前为止,您得到的答案确保
MIN = 15;行甚至不会编译,因此它也不会引发异常。 -
TS 可能并不是字面上的意思是他想要一行抛出异常,只是该行不会将常量 MIN 设置为一个值。
-
是的,不需要例外。只有唯一的值必须在运行时保持。
-
readonly就是这个意思。该值只能在构造函数中设置,之后为常量。
标签: c# variables constants readonly