Sph*_*hax 3 c# arrays multidimensional-array
我想使用2-D阵列但我不能提前知道它的大小.所以我的问题是:如何申报?然后如何在其中添加值?
String[,] tabConfig = new String[?, 4];
foreach(blabla with i)
{
tabConfig[i, 0] = a;
tabConfig[i, 1] = b;
tabConfig[i, 2] = c;
tabConfig[i, 3] = d;
}
Run Code Online (Sandbox Code Playgroud)
我知道我也可以使用列表,但我不是很熟悉它.
谢谢!
编辑:支持你自己!在Jon Skeet的帮助下,我的真实代码来了!
List<string[]> tabConfig = new List<string[]>();
String[] temp = new String[4];//The array that will be inside the List
int line = 0, column = 0;
foreach (XmlNode e in doc.DocumentElement.ChildNodes)
{
if (e.Attributes["Server"].Value == choice)
{
temp[0] = e.Attributes["Serveur"].Value;//Here is value 'a'
column = 1;
foreach (XmlNode i in e.ChildNodes)
{
temp[colonne] = i.InnerText;//Here are values 'b', 'c' and 'd'
column++;
}
tabConfig.Add(temp);//Put a new line into the List
line++;
}
}
Run Code Online (Sandbox Code Playgroud)
并称之为:
foreach(string[] array in tabConfig)
foreach(String txt in array)
Console.WriteLine(txt);
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 11
所以我的问题是:如何申报?
你不能..NET中的所有数组都是固定大小的:如果不知道大小,则无法创建数组实例.
它看起来像你应该有一个List<T>- 我实际上创建了一个类来保存这四个属性,而不是仅仅使用数组的四个元素.您可以使用数组列表:
List<string[]> tabConfig = new List<string[]>();
foreach (...)
{
tabConfig.Add(new string[] { a, b, c, d });
}
Run Code Online (Sandbox Code Playgroud)
...但是你需要知道这四个元素在排序等方面意味着什么,这可能会使你的其余代码更难理解.