尝试int.parse多数组字符串

Mic*_*ard 3 c# arrays for-loop multidimensional-array

我这样做:

string[,] string1 = {{"one", "0"},{"Two", "5"},{"Three","1"}};
int b = 0;

for(int i = 0; i <= string1.Length; i++)
{
     b = int.Parse(string1[i, 1]); // Error occurs here
}
Run Code Online (Sandbox Code Playgroud)

我得到一个错误说"索引范围数组的限制"(或类似的东西,错误是丹麦语).

Jon*_*eet 8

有两个问题:

  • string1.Length将返回6,因为这是数组的长度
  • <=用于比较,所以它实际上会尝试迭代7次.

你的for循环应该是:

for (int i = 0; i < string1.GetLength(0); i++)
Run Code Online (Sandbox Code Playgroud)

GetLength(0)此处的调用将返回3,作为"第一"维度的大小.调用GetLength(1)返回2,因为第二个维度的大小为2.(你不需要那个,因为你基本上硬编码你想要每个"行"的第二个"列"的知识.)

有关Array.GetLength()详细信息,请参阅文档.


Dan*_*zey 7

循环中的数组边界不正确:

for(int i = 0; i <= string1.Length; i++) 
Run Code Online (Sandbox Code Playgroud)

应该读:

for(int i = 0; i < string1.GetLength(0); i++) 
Run Code Online (Sandbox Code Playgroud)

有两件事情是错误的:<=<意味着你要去一个项目太远了,.Length返回(6)与该阵列的总长度GetLength(0)返回第一个维度(3)的长度.