尝试catch语句C#中的变量范围问题
我不想在这里问这个简单的问题,但是我已经研究了一段时间,但无济于事.这极大地限制了我的应用程序.
I hate to ask this simple of a question on here but I've researched this for a while and to no avail. And it's significantly limiting my application.
为什么我在try块内的excelWorksheet变量上出现红色波浪状(在此范围内不能声明名为"excelWorksheet"的本地或参数,因为该名称用于封闭的本地范围内).如果我删除了null声明,那么try catch语句之后的所有'excelWorksheet'实例将变为红色.非常感谢您的帮助.以下是代码:
Why am I getting a red squiggly on the excelWorksheet variable inside the try block (a local or parameter named 'excelWorksheet' cannot be declared in this scope because that name is used in an enclosing local scope). If I delete the null declaration, then all instances of 'excelWorksheet' after the try catch statement turn red. Any help is extremely appreciated.Here's the code:
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;
}
无法在此范围内声明名为"excelWorksheet"的本地或参数,因为该名称用于封闭的本地范围
您正试图重新声明该变量.删除声明,只使用封闭范围中声明的变量即可:
You're trying to re-declare the variable. Remove the declaration and simply use the variable that was declared in the enclosing scope:
string currentSheet = "Raw Data";
excelWorksheet = (Excel.Worksheet)ExcelSheets.get_Item(currentSheet);