【问题标题】:C# Why isn't this variable set if it's set?C#如果设置了这个变量,为什么不设置?
【发布时间】:2015-04-20 17:08:42
【问题描述】:

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

 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();
}

【问题讨论】:

  • 屏幕截图令人不快:(如果您可以实际粘贴代码,那就太好了。
  • 您可以在此处粘贴并格式化您的代码,请删除该图像并尝试使用 SO 文本编辑器
  • 你到底在问什么?需要更多细节。
  • 路径可能无效,检查是否捕获异常。
  • 因为它不是在所有条件下都设置的,如果你的 Try 抛出一个异常,它将继续下面的 for 循环,其中 Outpath 将为空。该 for 循环应该在 outpath 分配下的 Try...Catch 语句中。

标签: c# variables static-methods


【解决方案1】:

您的问题是您实际上在 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);
    }
}

【讨论】:

  • 您的第一个陈述不正确。范围是你声明变量的地方,而不是你定义它的地方……但是将循环移到 try{} 中是正确的方法,所以不会让你失望。
  • @KevinNelson 你能给我正确的术语,以便我更正它。我总是搞砸我的条件...
  • 我自己的术语很糟糕...但是您要避免的是未定义 OutPath 的空引用异常...不是因为块范围而是因为错误...因为他的 catch() 本质上只是忽略了错误,所以它继续运行,就好像它是一个有效的 StreamWriter。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-17
  • 2012-11-18
  • 1970-01-01
  • 2013-05-16
  • 2012-08-20
相关资源
最近更新 更多