一些全局变量只需要初始化一次。我通过加载文件并将其设置为任意值来实现。现在,当我尝试为这个变量设置一个新值时,我希望抛出一个异常。
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
}
}
我怎么做呢?
(可能很简单,我很抱歉)
创建一个静态构造函数,并将变量标记为只读。然后在构造函数中设置该值。
public static class Foo
{
public static readonly int MIN;
static Foo()
{
MIN = 18;
}
public static void Main()
{
}
}
public class Foo
{
public readonly static int MIN;
static Foo()
{
MIN = 18;
}
public static void Main()
{
}
}
如果您不能或不想使用其他答案中的静态构造函数(例如,因为在实际初始化变量之前您有很多与类型相关的事情要做,或者因为您意识到静态构造函数调试起来非常痛苦……),您可以使用其他方法:
一种编译时解决方案是将自己的类型中的变量打包为非静态只读,并保留对该类型的静态引用
public class Constants
{
public readonly int MIN;
public Constants() { MIN = 18; }
}
public class Foo
{
public static Constants GlobalConstants { get; private set; }
public static void Main()
{
// do lots of stuff
GlobalConstants = new GlobalConstants();
}
}
或者你可以把这个常量变成一个属性,只为你的类之外的任何人提供getter。注意,声明类仍然可以更改该属性。
public class Foo
{
public static int MIN { get; private set; } }
public static void Main()
{
MIN = 18;
MIN = 23; // this will still work :(
}
}
或者——如果出于某种奇怪的原因——你真的想要一个异常而不是编译错误,你可以从常量中创建一个属性,并在setter中抛出异常。
public class Foo
{
static int _min;
public static int MIN { get { return _min; } set { throw new NotSupportedException(); } }
public static void Main()
{
_min = 18;
}
}
与其使用公共成员变量,不如创建一个公共属性,然后在实现中管理CONST逻辑。
private static int? _min;
public static int MIN
{
set {
if (!_min.HasValue())
{
_min = value;
}
else
{
throw;
}
}
get {
return _min.ValueOrDefault();
}
}