我在尝试使用循环初始化一个数组(c#),但卡在这里了。行数将根据情况而变化。我需要得到之前在程序中计算的两个值startweek和endweek。有很多关于使用循环构建int数组的示例,但是我找不到关于动态字符串和多维数组的内容。
谢谢
如何为string[,] arrayWeeks = new string[numWeeks, col1];中的col1设置值?这样清楚吗?
我在尝试使用循环初始化一个数组(c#),但卡在这里了。行数将根据情况而变化。我需要得到之前在程序中计算的两个值startweek和endweek。有很多关于使用循环构建int数组的示例,但是我找不到关于动态字符串和多维数组的内容。
谢谢
如何为string[,] arrayWeeks = new string[numWeeks, col1];中的col1设置值?这样清楚吗?
感谢您的澄清。您可以这样做一个多维初始化器:
string[,] arrayWeeks = new string[,] { { "1", "2" }, { "3", "4" }, { "5", "6" }, { "7", "8" } };
或者,如果你的数组是不规则的:
string[][] arrayWeeks = new string[][]
{
new string[] {"1","2","3"},
new string[] {"4","5"},
new string[] {"6","7"},
new string[] {"8"}
};
arrayWeeks[x] = new string[y];
,其中x是你正在添加的行数,y是该行中元素的数量。然后你可以设置每个值:arrayWeeks[x][i] = ...
,其中i是行中设置的第i个元素。你的数组的初始声明应为string[][] arrayWeeks = new string[numRows][];
因此,总结一下,你可能需要的代码如下: int numRows = 2;
string[][] arrayWeeks = new string[numRows][];
arrayWeeks[0] = new string[2];
arrayWeeks[0][0] = "hi";
arrayWeeks[0][1] = "bye";
arrayWeeks[1] = new string[1];
arrayWeeks[1][0] = "aloha";
但显然,在您的循环内部。
在C#中,有两种你可能称之为“多维数组”的类型。其中一种是真正的多维数组:
string[,] array = new string[4, 4];
array[0, 0] = "Hello, world!";
// etc.
还有一种叫做锯齿数组的数组类型。锯齿数组是由元素也是数组的数组。在锯齿数组中,“行”可以拥有不同的长度。需要注意的是,在使用锯齿数组时,必须手动初始化“行”:
string[][] array = new string[4][];
for(int i = 0; i < 4; i++) {
array[i] = new string[4];
}
array[0][0] = "Hello, world!";
// rowCount from runtime data
stringArray = new string[rowCount][];
for (int index = 0; index < rowCount; index++)
{
// columnCount from runtime data
stringArray[index] = new string[columnCount];
for (int index2 = 0; index2 < columnCount; index2++)
{
// value from runtime data
stringArray[index][index2] = value;
}
}