C#为什么不设置此变量?

时间:2015-04-20 17:08:42

标签: c# variables static-methods

请帮忙。考虑到我缺乏编程知识,无法解决它。

 public static void FileOutput(string path, bool rewrite, List<int> NumberOfWords)
{
    StreamWriter OutPath;
    try
    {
        OutPath = new StreamWriter(path, rewrite);
    }
    catch(IOException e)
    {
        Console.WriteLine(e.Message);
    }

    for(int i = 0; i < NumberOfWords; i++)
    {
        try
        {
            OutPath.Write(NumberOfWords[i]);
        }
        catch(IOException e)
        {
            Console.WriteLine(e.Message);
        }
    }
    OutPath.Close();
}

1 个答案:

答案 0 :(得分:3)

您的问题是您实际在try-catch中设置了OutPath变量。这意味着您的变量仅在try-catch的范围内设置。试试这个

 public static void FileOutput(string path, bool rewrite, List<int> NumberOfWords)
{
    StreamWriter OutPath;
    try
    {
        OutPath = new StreamWriter(path, rewrite);

        for(int i = 0; i < NumberOfWords; i++)
        {
            try
            {
                OutPath.Write(NumberOfWords[i]);
            }
            catch(IOException e)
            {
                Console.WriteLine(e.Message);
            }
        }
    OutPath.Close();
    }
    catch(IOException e)
    {
        Console.WriteLine(e.Message);
    }
}