3

我有以下代码:

public Form1()
{
    InitializeComponent();


    string strRadio = Utils.ReadFile(strTemp + @"\rstations.txt");
    string[] aRadio = strRadio.Split(new string[] { "#" }, StringSplitOptions.RemoveEmptyEntries);    
    for (int i = 0; i < aRadio.Length; i += 2)
    {
       listBox.Items.Add(aRadio[i]);
    }

}

private void listBox_SelectedIndexChanged(object sender, EventArgs e)
{
    int index = listBox.SelectedIndex;
    MessageBox.Show(aRadio[(index+1)]);
}

现在错误是The name 'aRadio' does not exist in the current context. 其中来自MessageBox.Show(aRadio[(index+1)]);. 我需要将其声明aRadio为公开的还是什么?如果是这样,这将如何完成?

4

4 回答 4

21

您在aRadio构造函数中声明为局部变量。您需要将其声明为实例变量,并在构造函数中为其赋值:

// TODO: Give this a better name
private readonly string[] aRadio;

// TODO: Give your form a better name too
public Form1()
{
    InitializeComponent();

    // TODO: You might want to reconsider reading files in a GUI constructor, too
    // TODO: Use Path.Combine(strTemp, "rstations.txt" instead of concatenation
    string strRadio = Utils.ReadFile(strTemp + @"\rstations.txt");
    aRadio = strRadio.Split(new string[] { "#" },
                            StringSplitOptions.RemoveEmptyEntries);

    for (int i = 0; i < aRadio.Length; i += 2)
    {
       listBox.Items.Add(aRadio[i]);
    }
}

KeyValuePair<string, string>但是,如果您可以通过将自定义对象(或只是 a )添加到列表框并通过属性绑定显示部分来做得比这种方法更好,我不会感到惊讶。这样你就可以得到选定的项目而不是选定的索引......没有必要像这样保留文本/值对。

于 2012-04-23T13:27:42.003 回答
2
   private string[] aRadio;

    public Form1() { 
      InitializeComponent();       
      string strRadio = Utils.ReadFile(strTemp + @"\rstations.txt");
      this.aRadio = strRadio.Split(new string[] { "#" }, StringSplitOptions.RemoveEmptyEntries);
      for (int i = 0; i < aRadio.Length; i += 2)
      {
        listBox.Items.Add(aRadio[i]);
      }
    }

    private void listBox_SelectedIndexChanged(object sender, EventArgs e) {
      int index = listBox.SelectedIndex;
      MessageBox.Show(this.aRadio[(index+1)]);
    } 
于 2012-04-23T13:31:00.267 回答
1

您将访问在您的构造函数域中定义的变量,form1以便您可以执行此操作

//Define the variable as an attribute of class

private string[] strRadio;
public Form1()
{
        InitializeComponent();
        string strRadio = Utils.ReadFile(strTemp + @"\rstations.txt");
        aRadio = strRadio.Split(new string[] { "#" }, StringSplitOptions.RemoveEmptyEntries);

        for (int i = 0; i < aRadio.Length; i += 2)
        {
           listBox.Items.Add(aRadio[i]);
        }

    }

    private void listBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        int index = listBox.SelectedIndex;
        MessageBox.Show(aRadio[(index+1)]);
    }
}
于 2012-04-23T13:29:55.727 回答
-3

System.StringSplitOptions.RemoveEmptyEntries :以这种方式输入将解决您的问题。

不要问我为什么我只知道它是这样工作的。

于 2014-12-10T04:40:09.413 回答