首页 > 解决方案 > 当前上下文 C# 中不存在名称 VARname

问题描述

我知道有很多类似的问题/答案,但我无法根据我的问题调整解决方案:

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

在此处输入图像描述

标签: c#listboxvisual-studio-2019

解决方案


问题是语句后面的分号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());
}

推荐阅读