繁体   English   中英

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

[英]IEnumerable - implementing using GetEnumerator from local variable

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

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

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

        // ...
  }

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

Dictionary实现了IEnumerable<KeyValuePair<TKey, TValue>> ,所以这个工作原理:

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

您可以简单地提供一个公共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)
{
    ...
}

您只需返回errorList.GetEnumerator()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM