坚持二维数组

时间:2013-07-23 18:29:35

标签: c# arrays multidimensional-array

我正在尝试创建一个预订服务,我已经被困在这个部分好几个小时了,我只是无法弄清楚我做错了什么。

所以我有一个二维数组,当我在测试时试图打印出一些东西并试图弄清楚什么是错的,我得到的只是System.String[]这并不能让我更加明智。我希望能够访问m_nameMatrix[0,0]中的详细信息以检查座位是否被保留。

以下是我的表单代码中的代码段:

private void UpdateGUI(string customerName, double price)
{
    string selectedItem = cmdDisplayOptions.Items[cmdDisplayOptions.SelectedIndex].ToString();
    rbtnReserve.Checked = true;
    lstSeats.Items.Clear();
    lstSeats.Items.AddRange(m_seatMngr.GetSeatInfoStrings(selectedItem));
}

以下是我的第二节课的两种方法:

public string[] GetSeatInfoStrings(string selectedItem)
{
    int count = GetNumOfSeats(selectedItem);

    if (count <= 0)
    {
        return new string[0];
    }
    string[] strSeatInfoStrings = new string[count];

    for (int index = 0; index <= count; index++)
    {
        strSeatInfoStrings[index] = GetSeatInfoAt(index);
    }
    return strSeatInfoStrings;
}

public string GetSeatInfoAt(int index)
{
    int row = (int)Math.Floor((double)(index / m_totNumOfCols));
    int col = index % m_totNumOfCols;

    string seatInfo = m_nameMatrix.GetValue(row, col).ToString();
    return seatInfo;
}

我实际上并没有得到例外,所以我的逻辑思维可能是由于数小时和数小时试图弄清楚而受到重创。

编辑:

public void ReserveSeat(string name, double price, int index)
    {
        int row = (int)Math.Floor((double)(index / m_totNumOfCols));
        int col = index % m_totNumOfCols;

        string reserved = string.Format("{0,3} {1,3} {2, 8} {3, 8} {4,22:f2}",
                                        row + 1, col + 1, "Reserved", name, price);

        m_nameMatrix[row, col] = reserved;
    }

3 个答案:

答案 0 :(得分:1)

这一行:

for (int index = 0; index <= count; index++)

应该是:

for (int index = 0; index < count; index++)

为什么呢?假设我有一个包含2个对象的数组。 count将为2. 但是,索引为 0 1 。因此,您必须使用小于运算符。

答案 1 :(得分:1)

如果您在消息框中收到“System.String[]”,那是因为您尝试直接打印string[],而不是它包含的各种字符串:

string[] data = GetSeatInfoStrings("foo");
MessageBox.Show(data);

相反,您需要显示数据的内容

string[] data = GetSeatInfoStrings("foo");
MessageBox.Show(string.Join("\n", data));

有关文档,请参阅here

答案 2 :(得分:0)

假设您有一个名为ReturnArray()的方法:

class Class2
    {
        public string[] ReturnArray()
        {
            string[] str = new string[] { "hello", "hi" };
            return str;
        }

    }

如果您在主要课程中调用ReturnArray,请执行以下操作:

    Class2 class2 = new Class2();

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(class2.ReturnArray());
    }

它会返回System.String[],因为在这种情况下MessageBox.Show(...)会将string作为参数。

因此,使用MessageBox.Show(class2.ReturnArray().ToString());

也可以获得相同的结果

相反,你可能想要做这样的事情:

    Class2 class2 = new Class2();

    private void button1_Click(object sender, EventArgs e)
    {
        string[] strArray = class2.ReturnArray();
        listBox1.Items.AddRange(strArray);
    }
相关问题