我创建了此类:

class Riconoscimento
{
    private List<Word> words = new List<Word>();


    public List<Word> GetList()
    {
        return words;
    }

    public void loadWords()
    {
        string[] lines = File.ReadAllLines(Environment.CurrentDirectory + "/../../words.txt");
            foreach (string line in lines)
            {
                // skip commentblocks and empty lines..
                if (line.StartsWith("--") || line == String.Empty) continue;

                // split the line
                var parts = line.Split(new char[] { '|' });

                // add commandItem to the list for later lookup or execution
                words.Add(new Word() { Text = parts[0], AttachedText = parts[1], IsShellCommand = (parts[2]) });


            }
      }
}


但是在加载loadWords()之后,当我尝试从MainForm中的类中获取单词时,

 public void engine_WordsRecognized(object sender, SpeechRecognizedEventArgs e)
    {
        Riconoscimento _riconoscimento = new Riconoscimento();
        List<Word> words = _riconoscimento.GetList();
        var cmd = words.Where(c => c.Text == e.Result.Text).First();
}


错误发生:
  System.InvalidOperationException -Sequence不包含元素。

就像无法从类中检索单词,我不明白为什么。
如果我不使用该类,而是将所有内容都放入我的主代码中,那么它将起作用。
我该怎么办?

解决的问题:我在另一个void中加载了loadWords(),我不得不在另一个void中加载了它。

最佳答案

您不是在呼叫loadWords()。这就是为什么没有加载任何东西的原因。

public void engine_WordsRecognized(object sender, SpeechRecognizedEventArgs e)
{
    Riconoscimento _riconoscimento = new Riconoscimento();
    _riconoscimento.loadWords();
    List<Word> words = _riconoscimento.GetList();
    var cmd = words.Where(c => c.Text == e.Result.Text).First();
}

关于c# - 从类(class)中获取列表时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33639438/

10-12 23:07