变量在当前上下文中不存在

Avn*_*ner 2 c#

     I have the following code:


        try
        {
            FileStream FS = new FileStream(this.InFile, FileMode.Open, FileAccess.Read);
            return "";
        }
        catch (FileNotFoundException ex)
        {
            return ex.Message;
        }

        finally
        {
            FS.Close();
            FS.Dispose();
        }
Run Code Online (Sandbox Code Playgroud)

但是当我编译它时,我得到一个错误:在当前上下文中不存在名称"FS".

所以我在尝试..catch块之前将FileStream声明放在顶部

        FileStream FS;
        try
        {
            FileStream FS = new FileStream(this.InFile, FileMode.Open, FileAccess.Read);
            return "";
        }
        catch (FileNotFoundException ex)
        {
            return ex.Message;
        }

        finally
        {
            FS.Close();
            FS.Dispose();
        }
Run Code Online (Sandbox Code Playgroud)

但是当我编译时,我得到一个错误,说使用未分配的变量FS,它指向finally块.

现在我理解这两个错误以及为什么我得到它们但是我不知道如何编写它以便我尝试代码并捕获错误,如果有的话.

任何帮助将不胜感激 - 谢谢!

Mar*_*ell 10

其他回复涵盖了为什么(范围和确定的任务) - 但你正在努力生活......

try {
    using(FileStream FS = new FileStream(
        this.InFile, FileMode.Open, FileAccess.Read))
    {
        return "";
    }
} catch (FileNotFoundException ex) {
    return ex.Message;
}
Run Code Online (Sandbox Code Playgroud)


lag*_*neb 8

如果抛出FileNotFoundException会发生什么?然后你会得到finally子句(FS.Close()和FS.Dispose())但FS没有被初始化!你应该做的是将FS初始化为null,并在finally子句中添加一个if语句,检查FS是否为空

    FileStream FS = null;
    try
    {
        FS = new FileStream(this.InFile, FileMode.Open, FileAccess.Read);
        return "";
    }
    catch (FileNotFoundException ex)
    {
        return ex.Message;
    }

    finally
    {
        if (FS != null) {
            FS.Close();
            FS.Dispose();
        }
    }
Run Code Online (Sandbox Code Playgroud)