【问题标题】:How do I correctly wrap a Dictionary<T,U> and expose an enumerator?如何正确包装 Dictionary<T,U> 并公开枚举器?
【发布时间】:2012-05-23 03:08:24
【问题描述】:

我在我的对象中封装了一个字典。如何公开 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);
       }
}

【问题讨论】:

    标签: c# inheritance dictionary ienumerable encapsulation


    【解决方案1】:

    实现IEnumerable&lt;KeyValuePair&lt;int, SummaryEntity&gt;&gt;

    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);
       }
    }
    

    【讨论】:

    • 宾果游戏!我一直在弄清楚这应该去哪里!花了几个小时..谢谢! 38 秒后接受。
    猜你喜欢
    • 2011-04-08
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多