Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#为什么不';t如果该变量为';准备好了吗?_C#_Variables_Static Methods - Fatal编程技术网

C#为什么不';t如果该变量为';准备好了吗?

C#为什么不';t如果该变量为';准备好了吗?,c#,variables,static-methods,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) {

请帮忙。考虑到我缺乏编程知识,我无法解决这个问题

 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();
}
publicstaticvoidfileoutput(字符串路径、bool重写、列表NumberOfWords)
{
流线型书写器输出路径;
尝试
{
OutPath=新StreamWriter(路径,重写);
}
捕获(IOE异常)
{
控制台写入线(e.Message);
}
for(int i=0;i
您的问题是您实际上在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);
    }
}
publicstaticvoidfileoutput(字符串路径、bool重写、列表NumberOfWords)
{
流线型书写器输出路径;
尝试
{
OutPath=新StreamWriter(路径,重写);
for(int i=0;i
屏幕截图令人不快:(如果您可以实际粘贴代码,那就太好了。您可以在此处粘贴和格式化您的代码,请删除该图像并尝试使用SO文本编辑器。您到底在问什么?需要更多详细信息。路径可能无效,请检查它是否捕获异常。因为它不是在所有条件下都设置的,如果您的尝试引发exception它将在for循环下面继续,其中Outpath将为null。for循环应该在Outpath分配下的Try…Catch语句中。您的第一个语句不正确。作用域是您声明变量的位置,而不是定义变量的位置…而是将循环移动到Try{}是正确的方法,所以不会打倒你。@KevinNelson你能给我正确的术语吗,这样我就可以纠正它。我总是弄乱我的术语…我自己在术语上很糟糕…但是你试图避免的是一个空引用异常,其中未定义输出路径…不是因为块范围而是因为一个错误…因为s catch()实际上只是忽略了错误,它继续运行,就好像它是一个有效的StreamWriter一样。