我想给数组的每个元素命名。
这是我的代码:
string[] myArray = new string[5];
bool open = true;
while (open == true)
{
Console.WriteLine(
"Choose a number\n" +
"[1] Put in 5 names\n" +
"[2] Show all 5 names\n" +
"[3] Close\n");
Int32.TryParse(Console.ReadLine(), out int menu);
switch (menu)
{
case 1:
Console.WriteLine("\nWrite 5 letters\n");
for (int i = 0; i < myArray.Length; i++)
{
myArray[i] = Console.ReadLine();
}
Console.ReadLine();
break;
case 2:
Console.WriteLine("\nThese are the 5 letters:\n");
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine(myArray[i]);
}
Console.ReadLine();
break;
case 3:
open = false;
break;
}
我想要做的是,而不是像这样打印出数组(如果我将元素命名为 a、b、c、d、e):
a
b
c
d
e
我想在每个元素前面加上一个名字, 像这样:
[slot 1]: a
[slot 2]: b
[slot 3]: c
[slot 4]: d
[slot 5]: e
我还希望能够通过键入如下内容来打印出这封信:Console.WriteLine([slot 1]);
或者我必须写什么。
最佳答案
您正在寻找 Dictionary<String, String>
,不是数组。
var myDict = Dictionary<String, String>();
myDict["slot 1"] = "a";
myDict["slot 2"] = "b";
var x = myDict["slot 1"];
if (myDict.ContainsKey("slot 3"))
{
Console.WriteLine(myDict["slot 3"]);
}
等等
关于c# - 我可以用字符串变量(或其他东西)命名数组的每个元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46368304/