如何解决"使用未分配的局部变量"错误

-3 c# variable-declaration

出于某种原因,我的程序给了我一个错误,告诉我"使用未分配的局部变量'路径'",这真是太该死了,尝试重启视觉工作室(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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

spo*_*ger 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));

        }

    }
Run Code Online (Sandbox Code Playgroud)

我可能还会尝试一下...确保用户选择了一个有效的路径(不记得OpenFileDialog的默认值).