c# - 如何正确包装 Dictionary<T,U> 并公开枚举器?

标签 c# inheritance dictionary ienumerable encapsulation

我在我的对象中封装了一个字典。我如何公开 IEnumerable>?

之前

class HashRunningTotalDB : Dictionary<int, SummaryEntity>
{
         /... 
} 

// WORKS!
static void Main ()
{
       HashRunningTotalDB  tempDB = new HashRunningTotalDB();
       //todo: load temp DB

       foreach(var item in tempDB)
       {
           Console.Writeline(item.Key + " " + item.Value.SomeProperty);
       }
}

之后

class HashRunningTotalDB : IEnumerable
{
    Dictionary<int, SummaryEntity> thisHashRunningTotalDB = new Dictionary<int, SummaryEntity>();

      //QUESTION:  HOW DO I IMPLEMENT THE GENERIC ENUMERATOR HERE?
    // The following doesn't behave the same as the previous implementation
     IEnumerator IEnumerable.GetEnumerator()
    {
        return thisHashRunningTotalDB.GetEnumerator();
    }


    // The following doesn't compile
     Dictionary<int, SummaryEntity>.Enumerator IEnumerable<Dictionary<int, SummaryEntity>>.GetEnumerator()
    {
        return thisHashRunningTotalDB.GetEnumerator();
    }
} 



static void Main ()
{
       HashRunningTotalDB  tempDB = new HashRunningTotalDB();
       //todo: load temp DB


       // NOT WORKING
       foreach(var item in tempDB)
       {
           Console.Writeline(item.Key + " " + item.Value.SomeProperty);
       }
}

最佳答案

实现 IEnumerable<KeyValuePair<int, SummaryEntity>>

class HashRunningTotalDB : IEnumerable<KeyValuePair<int, SummaryEntity>>
{
   Dictionary<int, SummaryEntity> thisHashRunningTotalDB =
      new Dictionary<int, SummaryEntity>();

   public IEnumerator<KeyValuePair<int, SummaryEntity>> GetEnumerator()
   {
      return thisHashRunningTotalDB.GetEnumerator();
   }

   IEnumerator IEnumerable.GetEnumerator()
   {
      return GetEnumerator();
   }
}

static void Main()
{
   HashRunningTotalDB tempDB = new HashRunningTotalDB();

   // should work now
   foreach(KeyValuePair<int, SummaryEntity> item in tempDB)
   {
       Console.Writeline(item.Key + " " + item.Value.SomeProperty);
   }
}

关于c# - 如何正确包装 Dictionary<T,U> 并公开枚举器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10712933/

相关文章:

C# OpenXML 判断段落是否为隐藏文本

c++ - 强制派生类使用基类的构造函数

python - python 中深度复制的替代方案

c++ - 如果基类有两个同名函数,则找不到基类函数

java - 覆盖使用子类型的方法

testing - 如何使用 map 参数测试 XQuery 函数

ios - 选择器 'setRegion:animated:' 没有已知的类方法

c# - 带范围的数字的推荐组合算法

c# - 创建两个实现相同接口(interface)的单例服务

c# - 对数组内的范围进行排序以进行计数而不是逻辑排序