尝试catch语句C#中的变量范围问题 [英] Variable scope problems in try catch statement c#

查看:62
本文介绍了尝试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);

这篇关于尝试catch语句C#中的变量范围问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆