简体   繁体   中英

Assign static variable inside Class

I am trying to create a static variable inside class like below,

public class ClassEnLanguage
{
  public static Dictionary<string, string> dictionary = new Dictionary<string, string>();
}

this is no problem work fine even I can access this from other class, now I want to add values into dictionary object without using any method. like,

public class ClassEnLanguage
{
 public static Dictionary<string, string> dictionary = new Dictionary<string, string>();
    dictionary.Add("somekey1","someValue1");
    dictionary.Add("somekey2","someValue2");
}

Like in Java we can do like that,

public class ClassLanguageEn {
     public static HashMap labels = new HashMap();
        static {        
            labels.put("somekey1","someValue1");
            labels.put("somekey2","someValue2");
               }
}

and we can access this variable using ClassLanguageEn.labels (Classname.VariableName) .

Now my question is will it possible to do.

You can use a type initializer, or static constructor , like this:

public class ClassEnLanguage
{
    public static Dictionary<string, string> dictionary = new Dictionary<string, string>();
    static ClassEnLanguage()
    {
        dictionary.Add("somekey1","someValue1");
        dictionary.Add("somekey2","someValue2");
    }
}

Note that you can also use a dictionary initializer like this:

public class ClassEnLanguage
{
    public static Dictionary<string, string> dictionary = new Dictionary<string, string>
        {
            { "somekey1", "someValue1" },
            { "somekey2", "someValue2" }
        };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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