C# - 将变量标记为Const(只读)

时间:2013-06-05 13:23:35

标签: c# variables const readonly

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

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 个答案:

答案 0 :(得分:6)

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

public static class Foo
{
    public static readonly int MIN;

    static Foo()
    {
        MIN = 18;
    }

    public static void Main()
    {

    }
}

答案 1 :(得分:3)

public class Foo
{
    public readonly static int MIN;

    static Foo()
    {
        MIN = 18;
    }

    public static void Main()
    {
    }
}

答案 2 :(得分: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();
    }
}

或者你可以将常数变成属性,只为你班级以外的任何人提供吸气剂。请注意,声明类仍然可以更改属性。

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

答案 3 :(得分:0)

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

 private static int? _min;

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

    get {
           return _min.ValueOrDefault();
    }

 }
相关问题