C# 编译器错误表示我没有分配局部变量&;名称在当前上下文中不存在,而它存在吗?

C# 编译器错误表示我没有分配局部变量&;名称在当前上下文中不存在,而它存在吗?,c#,visual-studio,compiler-errors,unassigned-variable,C#,Visual Studio,Compiler Errors,Unassigned Variable,我写的这段代码,似乎有一些错误。以下是我遇到的错误: 对于loopteller++我得到一个错误“使用未分配的局部变量loopteller” 对于我所有的intpos,我得到这个错误“在当前上下文中不存在” 我的代码的目标是创建一个表单,当我单击按钮时,它可以读取文件并从文本文件中获取特定的单词。是的,我正在使用System.IO public Form1() { InitializeComponent(); } private void For

我写的这段代码,似乎有一些错误。以下是我遇到的错误:

对于
loopteller++我得到一个错误“使用未分配的局部变量loopteller”

对于我所有的
intpos
,我得到这个错误“在当前上下文中不存在”

我的代码的目标是创建一个表单,当我单击按钮时,它可以读取文件并从文本文件中获取特定的单词。是的,我正在使用
System.IO

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        string interface1 = "";
        string interface2 = "";
        string interface3 = "";
        string interface4 = "";
        int inpost1 = 0;
        int inpost2 = 0;
        int inpost3 = 0;
        int inpost4 = 0;
        int teller = 0;
        int interfaceteller = 0;
        int loopteller;


        string[] routerconfig = File.ReadAllLines("c:\\naamcomputer\\pt.txt");
        foreach(string configregel in routerconfig)
        {
            loopteller++;

            if (configregel.Contains("interface Gigabitethernet"))
            {
                teller++;
                if(teller == 1)
                {
                    interface1 = configregel;
                    intpos1 = loopteller;
                }
                else if(teller == 2)
                {
                    interface2 = configregel;
                    intpos2 = loopteller;
                }
                else if (teller == 3)
                {
                    interface3 = configregel;
                    intpos3 = loopteller;
                }
                else if (teller == 4)
                {
                    interface4 = configregel;
                    intpos4 = loopteller
                }
            }
        }

    }
}
对于loopteller++;我得到一个错误“使用未分配的局部变量loopteller”

这是真的,也正是问题所在。你从来没有分配过一个值,现在你想用
++
把它加起来。这不是它的工作原理。在使用所有其他变量之前,先给它赋值

对于我所有的intpos,我都会收到此错误“在当前上下文中不存在”

这是真的。您声明的变量命名为inpostX,而不是在tpos X中


简而言之:是的,你是对的。听一听,然后修复代码。

是的-您正在递增
loopteller
,但尚未为其指定初始值。你不能那样做。至于
intpos*
错误,请查看您实际声明的变量-
inpost1
,而不是
intpos1
。因此,这些只是输入错误(尽管您最好使用数组或集合)。