该名称在当前上下文中不存在。为什么?

时间:2016-02-27 14:47:30

标签: c#

我的代码是:

        if (textBox1.Text != "")
        {
            StreamReader tx = new StreamReader(textBox1.Text);
        }
        else
        {
            StreamReader tx = new StreamReader("new.txt");
        }

        string line;

        while ((line = tx.ReadLine()) != null)
        {

如果我删除“if”并将其保留为:

        StreamReader tx = new StreamReader("new.txt");


        string line;

        while ((line = tx.ReadLine()) != null)
        {

一切正常。为什么我的代码搞乱了?

1 个答案:

答案 0 :(得分:0)

将您的代码更改为:

   StreamReader tx;
   if (textBox1.Text != "")
   {
      tx = new StreamReader(textBox1.Text);
   }
   else
   {
      tx = new StreamReader("new.txt");
   }

您可以在此处了解详情:C# local variable scope