简体   繁体   English

如何为只读静态字段分配值

[英]how to assign value to readonly static field

I have a field which is static and readonly. 我有一个静态且只读的字段。 The requirement is that the value should be allocated to the field at the login time and after that it should be readonly. 要求是该值应在登录时分配给该字段,之后应为只读。 How can i achieve this ? 我怎样才能做到这一点?

  public static class Constant
    {
        public static readonly string name;                

    }

Kindly guide. 请指导。

If you declare a readonly field you can only set it in the constructor of the class. 如果声明一个只读字段,则只能在类的构造函数中进行设置。 What you could do is implementing a property only having a getter and exposing a change method that is used during your logon sequence to modify the value. 您可以做的就是实现一个仅具有吸气剂的属性,并公开一个在登录序列中用来更改值的更改方法。 Other Parts of your program can use the property effectivly not allowing them to change the value. 程序的其他部分可以有效地使用该属性,不允许它们更改值。

you need a static constructor 您需要一个静态构造函数

public static class Constant
{
    public static readonly string name;

    static Constant()
    {
        name = "abc";
    }
}
public static class Constant
{
    public static string Name
    {
        get
        {
            return name;
        }
        set
        {
            if (name == null)
                name = value;
            else
                throw new Exception("...");
        }
    }
    private static string name;
}

Just assign the value in the declaration (or constructor) like this: 只需在声明(或构造函数)中分配值,如下所示:

public static class Constant     
{
    public static readonly string name = "MyName";
} 

readonly is sugar for the compiler, telling him, that you don't intend to change the value outside the constructor. readonly是编译器的糖,告诉他,您不打算在构造函数外部更改值。 If you do so, he will generate an error. 如果这样做,他将产生一个错误。

You can also create a static constructor in your static class 您还可以在静态类中创建静态构造函数

static Constant()
{
    name = "Name";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM