我目前正在重構一些代碼,我偶然發現了這本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");
...
}
首先是在服務層中定義的,并且占用了很多空間 -400行,盡管它是static,但它似乎總是重新創建字典,這意味著它的靜態部分是多余的 - 或者我錯了嗎?
我如何確保只創建一次,并且每次呼叫它時,它都使用同一個實體。
uj5u.com熱心網友回復:
您說的很對,可以將本地字典提取為靜態成員
我建議這樣的東西(欄位):
// 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
};
uj5u.com熱心網友回復:
public static class Globals
{
static Dictionary<string, string>
CountryNamesAndCodes = new Dictionary<string, string>
{
{"AF", "Afghanistan"},
{"AL", "Albania"}
};
}
name = Globals.CountryNamesAndCodes["AF"];
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/445161.html
