我正在尝试使用for循环在C#中创建多个数组/字典

Joh*_*han 0 c# arrays dictionary for-loop

我正在尝试使用for循环在C#中创建多个数组/字典.我可以单独声明它们,但它不干净.

这是我的代码:

string[] names = ["dSSB", "dGEN", "dLYM", "dLUD", "dGGC", "dMAC", "dMMB"];

for (int i = 0; i <= names.Length; i++)
{
    string building = names[i];
    Dictionary<long, int> building = new Dictionary<long, int>();
}
Run Code Online (Sandbox Code Playgroud)

我试图使用存储在names数组中的名称来迭代创建数组.Visual Studio不接受已经声明的"构建".任何建议将不胜感激.谢谢!

D S*_*ley 5

在C#中没有办法创建动态命名的局部变量.

也许你想要一本字典词典?

string[] names = ["dSSB", "dGEN", "dLYM", "dLUD", "dGGC", "dMAC", "dMMB"];
var buildings = new Dictionary<string,Dictionary<long, int>>();

for (int i = 0; i <= names.Length; i++) {
      buildings[names[i]] = new Dictionary<long, int>();
}

//... meanwhile, at the Hall of Justice ...

// reference the dictionary by key string
buildings["dSSB"][1234L] = 5678;
Run Code Online (Sandbox Code Playgroud)