如何全局初始化全局嵌套字典?

时间:2016-03-27 18:15:05

标签: c# dictionary static initialization global-variables

我的字典声明如下:

private static Dictionary<string, Dictionary<string, string>> myDictionary;

我想全局初始化它。我最接近的是初始化外部词典,但仍然留下了对内部词典的空引用:

private static Dictionary<string, Dictionary<string, string>> myDictionary
 = new Dictionary<string, Dictionary<string, string>>();

我需要避免在方法中初始化它,因为我不想在能够使用我的类之前强制用户调用方法。用户只能访问静态方法。我可以在调用其中一种方法时创建一个单例,但这很脏。

如何在全球范围内声明这两个词典?其中一个(虽然都没有编译)的东西:

private static Dictionary<string, Dictionary<string, string>> myDictionary
 = new Dictionary<string, new Dictionary<string, string>>();

private static Dictionary<string, string> inner = new Dictionary<string, string>();
private static Dictionary<string, Dictionary<string, string>> myDictionary
 = new Dictionary<string, inner>();

2 个答案:

答案 0 :(得分:5)

像这样使用static constructor(假设myDictionary变量位于名为MyClass的类中):

public class MyClass
{
    private static Dictionary<string, Dictionary<string, string>> myDictionary;

    static MyClass()
    {
        //Initialize static members here
        myDictionary = new Dictionary<string, Dictionary<string, string>>();
        myDictionary.Add("mykey", new Dictionary<string, string>());
        ...
    }
}

框架将确保在访问类的任何成员之前自动执行静态构造函数。

答案 1 :(得分:4)

您可以通过遵循{} collection initialization syntax

来内联初始化,而无需在方法中执行此操作
private static Dictionary<string, Dictionary<string, string>> = new Dictionary<string, Dictionary<string, string>> {
    {   "first"
    ,   new Dictionary<string, string> {
            {"A", "one"}
        ,   {"B", "two"}
        }
    }
,   {   "second"
    ,   new Dictionary<string, string> {
            {"Y", "twenty five"}
        ,   {"Z", "twenty six"}
        }
    }
}