c# - 编译器错误说我没有分配局部变量并且名称在当前上下文中不存在,而它确实存在?

标签 c# visual-studio compiler-errors unassigned-variable

这段代码是我写的,好像有一些错误。这些是我收到的错误:

对于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
                }
            }
        }

    }
}

最佳答案

For loopteller++; I get a error "Use of unassigned local variable loopteller"

确实如此,正是哪里出了问题。您一开始就没有分配过值,现在您想使用 ++ 对其进行计数。事情不是这样的。在执行此操作之前为其分配一个值,您对所有其他变量都执行了此操作。

For all my intpos I get this error "Does not exist in the current context"

确实如此。您声明的变量被命名为 inpost X,而不是 intpos X

简而言之:是的,你的编译器是对的。听一下并修复您的代码。

关于c# - 编译器错误说我没有分配局部变量并且名称在当前上下文中不存在,而它确实存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47589774/

相关文章:

c++ - 未定义对在单独文件中定义的成员函数的引用

c# - 检查 FTP 上是否存在文件 - 不知道文件名

c# - Linq Union 的问题行为?

c# - 非常具体的 C# 到 VB.NET 的转换问题

c# - Entity Framework Core 在保存时不验证数据?

c# - 在代码 (.cs) 文件中插入图像

android - 无法从中加载模块元数据

visual-studio - 是否有 Visual Studio 宏可以在类中每个方法的开头设置断点?

visual-studio - 更新 Visual Studio 15 预览版

c++ - Eclipse C/C++ "Permission Denied"错误