C#如何使用另一个函数中的值?

时间:2010-09-13 21:44:48

标签: c# function button

如何使用reading函数中button1_Click函数的值?

public void reading(object sender, EventArgs e)
{
   DialogResult reading_from_folder = new DialogResult();
   reading_from_folder = folderBrowserDialog1.ShowDialog();

   if (reading_from_folder == DialogResult.OK)
   {
      string[] files_in_folder = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
      ...
   }
}

private void button1_Click(object sender, EventArgs e)
{ 
   foreach (string file in files_in_folder) // How do I access files_in_folder?
   {
      ListViewItem li = new ListViewItem(file);
   }
}                

2 个答案:

答案 0 :(得分:1)

您需要以某种方式存储它,例如作为私人成员:

string some_value = null;

public void reading(object sender, EventArgs e)
{
    some_value = "Foobar";
}

private void button1_Click(object sender, EventArgs e)
{
    if (some_value != null)
    {
        // ...
    }
}

答案 1 :(得分:1)

// Make it a member variable
private string[] mFilesInFolder = null;

public void reading(object sender, EventArgs e) 
{ 
    DialogResult reading_from_folder = new DialogResult(); 
    reading_from_folder = folderBrowserDialog1.ShowDialog(); 

    if (reading_from_folder == DialogResult.OK) 
    { 
       mFilesInFolder = Directory.GetFiles(folderBrowserDialog1.SelectedPath); 
    }
}  

private void button1_Click(object sender, EventArgs e) 
{   
   DoFileInFolderOperation();
}

private void DoFilesInFolderOperation()
{
   if(mFilesInFolder != null)
   {
      foreach (string file in mFilesInFolder) 
      { 
         ListViewItem li = new ListViewItem(file); 
      }
   } 
}