只创建一次字典 - 并在调用字典时使用它?

Only create dictionary once - and use that when dictionary is being called?

我目前正在重构一些代码,在那里我偶然发现了这个static字典:

public static Dictionary<string, string> CountryNamesAndCodes()
{
    var dictionary = new Dictionary<string, string>();
   
    dictionary.Add("AF", "Afghanistan");
    dictionary.Add("AL", "Albania");
    dictionary.Add("DZ", "Algeria");
    dictionary.Add("AD", "Andorra");
    dictionary.Add("AO", "Angola");
    dictionary.Add("AG", "Antigua and Barbuda");
    dictionary.Add("AR", "Argentina");
    dictionary.Add("AM", "Armenia");
    ...
}

首先是在服务层定义的,占了space-400行,虽然是static,但好像总是recreate字典,意味着使它的静态部分变得多余 - 或者我错了吗?

如何确保只创建一次,并且每次调用它时,它都使用同一个实例。

public static class Globals
{
    static Dictionary<string, string> 
    CountryNamesAndCodes = new Dictionary<string, string>
    {   
        {"AF", "Afghanistan"},
        {"AL", "Albania"}
    };
}

name = Globals.CountryNamesAndCodes["AF"];

你说得很对,你可以提取local字典作为static成员

我建议这样(字段):

// static readonly (we want to create it once) field of
// IReadOnlyDictionary type - we want to read key value pairs after its creation 
private static readonly IReadOnlyDictionary<string, string> countries = 
  // We may want to be nice and let ignore case for keys  
  new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
    { "AF", "Afghanistan" },
    { "AL", "Albania" },
    { "DZ", "Algeria" },
    //TODO:Put all the other records here    
  };

或者像这样 (属性):

// static readonly (there's no "set") property of
// IReadOnlyDictionary type - we want just to read key value pairs after its creation 
private static IReadOnlyDictionary<string, string> Countries { get; } = 
  new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
    { "AF", "Afghanistan" },
    { "AL", "Albania" },
    { "DZ", "Algeria" },
    //TODO:Put all the other records here
};