Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# IEnumerable-从局部变量使用GetEnumerator实现_C#_Ienumerable - Fatal编程技术网

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

C# IEnumerable-从局部变量使用GetEnumerator实现,c#,ienumerable,C#,Ienumerable,我是泛型/迭代器/枚举器等方面的新手 我有代码,它为每个字段保留字段号(int)和错误表(列表字符串): public class ErrorList : IEnumerable // ? { private Dictionary <int, List<string>> errorList; // ... } 公共类错误列表:IEnumerable/? { 私人字典错误列表; // ... } 如何使这个类与foreach

我是泛型/迭代器/枚举器等方面的新手

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

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

        // ...
  }
公共类错误列表:IEnumerable/?
{
私人字典错误列表;
// ...
}

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

字典实现了
IEnumerable
,因此它可以工作:

foreach (KeyValuePair<Int, List<String>> kvp in errorList) {
    var idx = kvp.Key;
    var vals = kvp.Value;
    // ... do whatever here
}
foreach(错误列表中的KeyValuePair kvp){
var idx=kvp.Key;
var VAL=kvp.值;
//……在这里做什么都行
}

您只需提供一个公共的
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();
    }
}
您可以循环浏览它们:

foreach (KeyValuePair<int, List<string>> item in errors)
{
    ...
}
foreach(错误中的KeyValuePair项)
{
...
}

您只需返回
errorList.GetEnumerator()

要枚举什么?信息?错误号码?两者的组合?编辑:我想使用字典枚举器(GetEnumerator)。顺便说一句:errorList不是一个局部变量,它是一个私有字段。尽管我肯定会在
foreach
上粘贴一个
var
,如
foreach(errorList中的var kvp){…}
Sure-我这样做是为了显示循环变量的类型。不需要接口。
foreach
循环所需要的只是一个名为
GetEnumerator
的公共方法,它返回一个
IEnumerator
。耶,你解决了它。现在我理解了这个没有接口继承的方法声明。@DarinDimitrov它甚至不必返回
IEnumerator
。要返回带有
Current
属性和
MoveNext
方法的内容。@phoog我通常会将接口放在我自己身上,我只是觉得
foreach
完全依赖duck类型很有趣。@vcsjones是的,我同意这很有趣。它主要是前泛型世界的遗迹,在这个世界中,duck类型是避免值类型元素集合受到装箱惩罚所必需的。还值得注意的是,实现接口对于使用linq的自定义集合是必要的。
foreach (KeyValuePair<int, List<string>> item in errors)
{
    ...
}