创建数组时出现C#错误

我需要为二维数组赋值。 我可以使用多个“myArray [x,y]”语句来完成它,但我想使用另一种方法(因为我将拥有包含许多行/列的数组) – 请参阅代码:

int x; x = 1; string[,] myArray = new string[2, 2]; if (x == 1) { //does not work : why? Would be easier to populate a big array using this //myArray= //{ // {"1", "1" }, // {"1", "1" } //} ; //works, but I need above code to work if possible myArray[0, 0] = "1"; myArray[0, 1] = "1"; myArray[1, 0] = "1"; myArray[1, 1] = "1"; } else if (x == 2) //does not work //myArray= //{ //{"2", "2" }, //{"2", "2" } //} ; myArray[0, 0] = "2"; myArray[0, 1] = "2"; myArray[1, 0] = "2"; myArray[1, 1] = "2"; } MessageBox.Show(myArray[0,0]); 

谢谢

正如您所提到的那样,您需要以这种方式使用它,然后您可以通过声明临时变量初始化其上的值然后将temp变量设置为公共变量来执行变通方法,如下所示:

 int x; x = 1; string[,] myArray = new string[2, 2]; if (x == 1) { string[,] myArrayTemp = { {"1", "1" }, {"1", "1" } }; } else if (x == 2) { string[,] myArrayTemp = { {"2", "2" }, {"2", "2" } }; myArray = myArrayTemp; } 

我不知道你是否特意想要对这些值进行硬编码,但是如果你知道数组的尺寸始终为[2, 2]你可以循环遍历所需的x值。

 var totalEntries = 10; for (var x = 1; x <= totalEntries; x++) { for (var i = 0; i < 2; i++) { for (var j = 0; j < 2; j++) { myArray[i, j] = x.toString("G"); } } } 

为什么不呢:

 if(x == 1 || x == 2) { for(int row = 0; row < ROW_COUNT; row ++) { for(int col = 0; col < COL_COUNT; col++) { myArray[row, col] = x.ToString(); } } } 

不确定条件if对您的情况有影响。

如果您正在询问其他事项,请澄清。

您还应该考虑使用循环来填充大型数组。

 var size = 1; for(int i = 0; i <= size; i++) { myArray[0, i] = x.ToString(); myArray[i, 0] = x.ToString(); } 

参考你提出的另一个问题 ,只需这样试试:

  int x; x=1; string[,] myArray; switch (x) { case 1: myArray = new string[,]{ { "1", "1" }, { "1", "1" } }; //OK break; case 2: myArray = new string[,]{ { "2", "2" }, { "2", "2" } }; //OK break; } 

你不能缩短这些作业,即myArray = { { "2", "2" }, { "2", "2" } }; 不允许(语法错误),因为在C#中string[,]如果不想事先指定数组大小,则始终需要new关键字来创建新对象和数据类型,即string[,] (对于二维数组)(你不需要这样计算元素)。