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

Bit*_*lue 1 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
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点 ?

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

Sam*_*emi 6

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

public static class Foo
{
    public static readonly int MIN;

    static Foo()
    {
        MIN = 18;
    }

    public static void Main()
    {

    }
}
Run Code Online (Sandbox Code Playgroud)