如何正确包装字典 并公开枚举器?

问题描述 投票:4回答:1

我正在将字典封装在我的对象中。如何公开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个回答
7
投票

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

0
投票

使用它有什么问题吗?

class HashRunningTotalDB : Dictionary<int, SummaryEntity> {}

© www.soinside.com 2019 - 2024. All rights reserved.