try catch语句c#中的变量范围问题

Variable scope problems in try catch statement c#

我不想在这里问这个简单的问题,但我已经研究了一段时间但无济于事。它极大地限制了我的应用程序。

为什么我在 try 块内的 excelWorksheet 变量上出现红色波浪线(无法在此范围内声明名为 'excelWorksheet' 的局部参数或参数,因为该名称用于封闭的局部范围)。如果我删除 null 声明,则 try catch 语句后 'excelWorksheet' 的所有实例都会变为红色。任何帮助都非常 appreciated.Here 的代码:

 Excel.Worksheet excelWorksheet = null;          
        try
        {
            //declare the worksheet variable raw data
            string currentSheet = "Raw Data";
            Excel.Worksheet excelWorksheet = (Excel.Worksheet)ExcelSheets.get_Item(currentSheet);
        }
        catch(Exception r)
        {
            MessageBox.Show("The Raw Data sheet in the report does not exist. " + r);
            return;
        }

a local or parameter named 'excelWorksheet' cannot be declared in this scope because that name is used in an enclosing local scope

您正在尝试重新声明变量。删除声明并简单地使用在封闭范围内声明的变量:

string currentSheet = "Raw Data";
excelWorksheet = (Excel.Worksheet)ExcelSheets.get_Item(currentSheet);

你能试试下面的吗?

Excel.Worksheet excelWorksheet = null;          
            try
            {
                //declare the worksheet variable raw data
                string currentSheet = "Raw Data";

//excelWorksheet variable already exists in the scope, so no need to declare it again

                excelWorksheet = (Excel.Worksheet)ExcelSheets.get_Item(currentSheet);
            }
            catch(Exception r)
            {
                MessageBox.Show("The Raw Data sheet in the report does not exist. " + r);
                return;
            }
Excel.Worksheet excelWorksheet = null;          

通过上面的语句,您已经声明了 excelWorksheet 变量。您无需再次申报。代码如下:

Excel.Worksheet excelWorksheet = null;          
            try
            {
                //declare the worksheet variable raw data
                excelWorksheet = ExcelSheets.get_Item("Raw Data") as Excel.Worksheet;
            }
            catch(Exception r)
            {
                MessageBox.Show("The Raw Data sheet in the report does not exist. " + r);
                return;
            }

用于铸造。这是一个很好的做法。