"Wrong number of indices inside [];expected 2" C# 中的二维数组错误

"Wrong number of indices inside [];expected 2" error for two-dimensional array in C#

您好,我是初学者 c# 学习者,据我所知,我在这里做错了,但不知道在哪里,有人知道吗?

namespace translateTelNum
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        String originalContent = "";
        originalContent = box1.Text.ToUpper();

        char[,] charGroup = new char[,]
       {
        {'A','B','C' }, 
        {'D','E','F' },              
        {'G','H','I' }, 
        {'J','K','L' }, 
        {'M','N','O' },
        {'P','R','S' }, 
        {'T','U','V' }, 
        {'W','X','Y' } 
       };

        String numbers = "";

        for (int i = 1; i <= originalContent.Length; i++)
        {
            for (int a = 1; a <= charGroup.Length; a++)
            {
                for (int b = 1; b <= charGroup[a].Length; b++)
                {
                    if (originalContent[i] == charGroup[a][b])
                    {
                        numbers += a + 2;
                    }
                }
            }
            if (i == 2 && i== 7)
            {
                numbers += "-";
            }
        }

        Console.WriteLine(numbers);
    }
}
}

以下行的错误 "Wrong number of indices inside [];expected 2":

for (int b = 1; b <= charGroup[a].Length; b++)
    if (originalContent[i] == charGroup[a][b])

而不是使用

for (int a = 1; a <= charGroup.Length; a++)
{
    for (int b = 1; b <= charGroup[a].Length; b++)
    {
        if (originalContent[i] == charGroup[a][b])

你应该使用

for (int a = 1; a <= charGroup.GetLength(0); a++)
{
    for (int b = 1; b <= charGroup.GetLength(1); b++)
    {
        if (originalContent[i] == charGroup[a,b])

有两处需要更改。

首先,您应该使用方法 GetLength(dimension) 来获取特定维度的长度,而不是使用 charGroup.LengthcharGroup[a].Length。因此,在这种情况下,为了获得行数,您应该使用 GetLength(0) 并获得列数,您应该使用 GetLength(1)。参见 documentation of GetLength on MSDN

其次,C# 多维数组由 array[index1, index2, ..., indexN] 而不是 array[index1][index2] ... [indexN] 访问。参见 documentation on MSDN

另外请记住,C# 中数组的索引从 0 开始,因此您的循环很可能应该从 0 而不是 1 开始:

for (int a = 0; a < charGroup.GetLength(0); a++)
{
    for (int b = 0; b < charGroup.GetLength(1); b++)
    {
        if (originalContent[i] == charGroup[a,b])