IEnumerable - 从局部变量使用GetEnumerator实现

时间:2012-03-23 17:53:46

标签: c# ienumerable

我是gebics / iterators / enumerators等的新手。

我有代码,它为每个字段保留字段编号(int)和错误消息(列表字符串):

  public class ErrorList : IEnumerable // ?
  {
        private Dictionary <int, List<string>> errorList;

        // ...
  }

如何让这个类与foreach循环一起工作?我想使用GetEnumerator表单字典,但我该怎么做呢?

3 个答案:

答案 0 :(得分:1)

字典实现IEnumerable<KeyValuePair<TKey, TValue>>,所以这有效:

foreach (KeyValuePair<Int, List<String>> kvp in errorList) {
    var idx = kvp.Key;
    var vals = kvp.Value;
    // ... do whatever here
}

答案 1 :(得分:1)

您只需提供公开GetEnumerator方法:

public class ErrorList
{
    private Dictionary<int, List<string>> errorList = new Dictionary<int, List<string>>();

    ... some methods that fill the errorList field

    public IEnumerator<KeyValuePair<int, List<string>>> GetEnumerator()
    {
        return errorList.GetEnumerator();
    }
}

现在假设您有一个ErrorList实例:

var errors = new ErrorList();

你可以循环使用它们:

foreach (KeyValuePair<int, List<string>> item in errors)
{
    ...
}

答案 2 :(得分:0)

您只需返回errorList.GetEnumerator()