我正在尝试在类中创建一个静态变量,如下所示
public class ClassEnLanguage
{
public static Dictionary<string, string> dictionary = new Dictionary<string, string>();
}
这是没问题的工作,即使我可以从其他类访问它,现在我想在不使用任何方法的情况下将值添加到字典对象中。等,
public class ClassEnLanguage
{
public static Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("somekey1","someValue1");
dictionary.Add("somekey2","someValue2");
}
就像在Java中一样,我们可以这样做,
public class ClassLanguageEn {
public static HashMap labels = new HashMap();
static {
labels.put("somekey1","someValue1");
labels.put("somekey2","someValue2");
}
}
我们可以使用ClassLanguageEn.labels (Classname.VariableName)
访问此变量。
现在我的问题是可以做到的。
答案 0 :(得分:3)
您可以使用类型初始值设定项,或static constructor,如下所示:
public class ClassEnLanguage
{
public static Dictionary<string, string> dictionary = new Dictionary<string, string>();
static ClassEnLanguage()
{
dictionary.Add("somekey1","someValue1");
dictionary.Add("somekey2","someValue2");
}
}
请注意,您还可以使用这样的字典初始值设定项:
public class ClassEnLanguage
{
public static Dictionary<string, string> dictionary = new Dictionary<string, string>
{
{ "somekey1", "someValue1" },
{ "somekey2", "someValue2" }
};
}