在c# VS2013中使用IEnumerator和GetEnumerator同时迭代3个字典

本文关键字:GetEnumerator 迭代 字典 3个 IEnumerator VS2013 | 更新日期: 2023-09-27 18:18:28

我需要从c# VS2013中一起迭代3个字典。

  // got error: Cannot implicitly convert type 'System.Collections.Generic.Dictionary<double,double>.Enumerator' to 'System.Collections.Generic.IEnumerator<System.Collections.Generic.Dictionary<double,double>>'
  using (IEnumerator<Dictionary<double,double>> iterator1 = dict1.GetEnumerator())  
  using (IEnumerator<Dictionary<double,double>> iterator2 = dict2.GetEnumerator())
  using (IEnumerator<Dictionary<double,double>> iterator3 = dict3.GetEnumerator())
  while (iterator1.MoveNext() && iterator2.MoveNext() && iterator3.MoveNext())
  {
      iterator1.Current. // I need to access key and values of dict1 here. Why none of them can be accessed here  ?
  }

在c# VS2013中使用IEnumerator和GetEnumerator同时迭代3个字典

Dictionary<K,V>的枚举器将实现IEnumerator<KeyValuePair<K, V>>

但这确实是var使事情变得更容易的情况:

using (var iterator1 = dict1.GetEnumerator())  
using (var iterator2 = dict2.GetEnumerator())
using (var iterator3 = dict3.GetEnumerator())
…

将鼠标悬停在Visual Studio中的var上,将告诉您推断的类型,您只需要指定类型,如果您需要覆盖该推断(在这种情况下,它可能是Dictionary<T,V>用于实现IEnumerator<…>的helper类型)。