繁体   English   中英

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

[英]C# How do I use a value from one function in another?

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

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);
   }
}                

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

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)
    {
        // ...
    }
}
// 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); 
      }
   } 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM