Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我正在尝试使用for循环在C中创建多个数组/字典_C#_Arrays_For Loop_Dictionary - Fatal编程技术网

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

C# 我正在尝试使用for循环在C中创建多个数组/字典,c#,arrays,for-loop,dictionary,C#,Arrays,For Loop,Dictionary,我正在尝试使用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 Dict

我正在尝试使用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>();
}

我试图使用存储在names数组中的名称来迭代创建数组。Visual Studio不接受已声明的建筑。如有任何建议,将不胜感激。谢谢大家!

在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;

你可以这样试试

        string[] names = {"dSSB", "dGEN", "dLYM", "dLUD", "dGGC", "dMAC", "dMMB"};
        Dictionary<string, Dictionary<long, int>> buildings = new Dictionary<string, Dictionary<long, int>>();
        for (int i = 0; i <= names.Length -1; i++) 
        {
            buildings[names[i]] = new Dictionary<long, int>();
            buildings[names[i]].Add(5L, 55);
        }

        //Here you can get the needed dictionary from the 'parent' dictionary by key
        var neededDictionary = buildings["dSSB"];

干杯

如果你只是想编一本字典,然后把东西放进去:

        Dictionary<int, string> buildings = new Dictionary<int, string>();

        string[] names = { "dSSB", "dGEN", "dLYM", "dLUD", "dGGC", "dMAC", "dMMB" };
        for (int i = 0; i < names.Length; i++)
        {
            buildings.Add(i, names[i]);
        }

        foreach (KeyValuePair<int, string> building in buildings)
        {
            Console.WriteLine(building);
        }

那么您想根据其他数据确定局部变量的名称?那是不可能的。为什么变量名是什么很重要?你拿字典干什么?@D Stanley……与此同时,在司法厅。。。哈哈哈,这让我笑了:谢谢你的回答。我正在尝试创建一个数据结构,我可以序列化它来创建一个JSON文件。谢谢你的回答!我在想:为什么要用var代替dictionary?有优势吗?没有优势,这也被认为是一种不好的做法,因为可读性较差。CLR将在编译时解析变量的类型。请参阅P.S.上的更多信息。很抱歉最近的回答。那么,building是表示键的通用变量吗?不。我不应该在这个示例中使用var关键字。建筑是一对钥匙。我想我可以解决它。var可能是一个令人沮丧的词。查一查。它是将变量强类型化为指定类型的简写。var chicken=new chicken是chicken=new chicken的同义词;