当前上下文中不存在名称 VARname C#

The name VARname does not exist in the current context C#

我知道有很多类似的 questions/answers 但我无法从中找到适合我的问题的解决方案:

我正在尝试迭代、遍历列表框的项目(所有元素都是路径),我想通过单击按钮使用默认 windows 程序打开它们。任何帮助将不胜感激。

问题是 foreach 语句后的分号。分号立即结束 foreach 语句。您上面的代码等同于:

foreach (string myitem in this.listBox1.Items)
{
  // myitem is only available in this scope
}

MessageBox.Show(myitem.toString(), "My Caption", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process.Start(myitem.ToString());

您需要将您想要的所有内容封装在 foreach 中,如下所示:

foreach (string myitem in this.listBox1.Items)
{
  MessageBox.Show(myitem.toString(), "My Caption", MessageBoxButtons.OK, MessageBoxIcon.Information);
  System.Diagnostics.Process.Start(myitem.ToString());
}