出于某种原因,我的程序给了我一个错误,告诉我“使用未分配的局部变量'路径'”,这真是太该死了,尝试重启视觉工作室(2017社区)几次并无济于事,试图重建解决方案......出于某种原因没有任何工作......
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace InterfacedStorage
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
OpenFile();
}
public void OpenFile()
{
OpenFileDialog openFile = new OpenFileDialog();
string path; // Declared path
if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
path = openFile.FileName; // Input path from a file
}
Excel excel = new Excel(path, 1); // Path is not declared...
MessageBox.Show(excel.ReadCell(0, 0));
}
}
}
答案 0 :(得分:5)
不能同意其他两个答案,因为他们忽略了用户可能没有选择文件的事实。 "Use of unassigned local variable"
我会按如下方式重组/编辑该功能
public void OpenFile()
{
OpenFileDialog openFile = new OpenFileDialog();
if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = openFile.FileName; // Input path from a file
Excel excel = new Excel(path, 1); // Path is not declared...
MessageBox.Show(excel.ReadCell(0, 0));
}
}
我可能还会尝试一下...以确保用户选择了有效的路径(不记得OpenFileDialog的默认值)。