1

我的一些全局变量只需要启动一次。我通过加载文件并将它们设置为任何内容来做到这一点。现在我想当我尝试为这个变量设置一个新值时抛出一个异常。

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
    }
}

我怎样才能做到这一点 ?

(可能很容易,我很抱歉)

4

4 回答 4

6

创建一个静态构造函数,并将变量标记为只读。然后在构造函数中设置值。

public static class Foo
{
    public static readonly int MIN;

    static Foo()
    {
        MIN = 18;
    }

    public static void Main()
    {

    }
}
于 2013-06-05T13:24:18.650 回答
3
public class Foo
{
    public readonly static int MIN;

    static Foo()
    {
        MIN = 18;
    }

    public static void Main()
    {
    }
}
于 2013-06-05T13:25:44.250 回答
2

如果您不能或不想使用其他答案中的静态构造函数(例如,因为在实际初始化变量之前您有很多与类型有关的事情,或者因为您意识到静态构造函数是一个真正的痛苦调试..)你可以做其他事情:


一种编译时解决方案是将您自己类型中的变量打包为非静态只读,并持有对该类型的静态引用

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;
    }
}
于 2013-06-05T13:38:18.637 回答
0

您可以创建一个公共属性,然后在您的实现中管理您的 CONST 逻辑,而不是拥有一个公共成员变量。

 private static int? _min;

 public static int MIN
 {
    set { 
            if (!_min.HasValue())
            {
                _min = value;
            }
            else
            {
               throw;
            }
    }

    get {
           return _min.ValueOrDefault();
    }

 }
于 2013-06-05T13:29:17.603 回答