c# - 为什么一行错误而另一行没有错误?

我的问题确实很简单,但Google的工作时间却无法解决我(显然)的独特情况。
问题是在以下代码中使用了未分配的变量

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleBasicCompiler
{
    class Lines : System.Collections.IEnumerable
    {
        // Variables
        private ArrayList<string> lines;

        // Constructor
        public Lines()
        {
            lines = new ArrayList();
        }

        public void Add(string line)
        {
            lines.add(line);
        }

        // Iterator
        public System.Collections.IEnumerator GetEnumerator()
        {
            for (int i = 0; i < lines.length(); i++)
            {
                yield return lines[i];
            }
        }

        public void Print()
        {
            foreach (string line in lines)
            {
               XFormMain.SetStatus(line); // this line errors
               System.Console.Write(line); // this line dosn't
            }
        }

    } // End Class Lines
} // End namespace

我的问题是为什么?
我无法更改声明,否则它将使迭代器语法无效
我什至尝试了以下
public void Print()
    {
        string lineB = "";
        foreach (string line in lines)
        {
           lineB = line; // now this line errors
           XFormMain.SetStatus(lineb); // and this line doesn't
           System.Console.Write(line); // this line doesn't in either situation
        }
    }

我想我是否知道为什么一条线有效,而一条线不行,但是.....有什么想法吗?

最佳答案

您发布的代码存在严重问题(即使没有Print方法,也无法编译)。不存在ArrayList<T>类。我认为那应该是List<string>。我还没有看到ArrayList的适当用法。

您收到的错误可能是因为ArrayList未类型化(这使它成为了糟糕的列表实现),但是您正在向其询问字符串。编译器知道它可能包含任意对象,并且使您无法假设它只有字符串。

我想第二行没有出错的原因是因为编译器在遇到第一个错误时停止了。

https://stackoverflow.com/questions/10507645/

相关文章:

java - 字符串预期错误?

haskell - Haskell语法错误

java - Java-无效的方法声明;方法的返回类型

vb.net - Git编译错误

c++ - 构建游泳池类时发生编译器错误

java - Java-ArrayOutOfBoundsException帮助我

java - 无缘无故的错误

objective-c - 预期标识符 '('

java - 参数数组字符串Jframe

ant - javac错误使用-source 5或更高版本来启用泛型