【问题标题】:The name does not exist in the current context. Why? [duplicate]当前上下文中不存在该名称。为什么? [复制]
【发布时间】:2016-02-27 14:47:29
【问题描述】:

我的代码是:

        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)
        {

一切正常。为什么 if 会弄乱我的代码?

【问题讨论】:

  • 在块 { ... } 内声明的变量仅在该块内可见。在 if { } 块内声明 StreamReader 不允许在其外部使用它,在方法块内声明它允许它在该方法块内的任何地方使用。这是用 C# 编程所需的基本知识(这个概念在任何地方都很有用)。请阅读一些关于C# Scopes

标签: c#


【解决方案1】:

将您的代码更改为:

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

您可以在这里了解更多信息:C# local variable scope

【讨论】:

    猜你喜欢
    • 2012-09-12
    • 1970-01-01
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    相关资源
    最近更新 更多