C#inheritance自Dictionary,迭代KeyValuePairs

我有一个inheritance自Dictionary 。 在实例方法中,我想迭代所有KeyValuePair 。 我尝试过以下操作:

 foreach (KeyValuePair pair in base) 

但是这失败了以下错误:

在此上下文中使用关键字“base”无效

如何在从Dictionary派生的类中的实例方法中迭代KeyValuePair Dictionary

编辑:我发现我可以执行以下操作:

 var enumerator = base.GetEnumerator(); while (enumerator.MoveNext()) { KeyValuePair pair = enumerator.Current; } 

但是,我仍然想知道是否有办法通过foreach循环执行此操作。

编辑:感谢有关不从Dictionaryinheritance的建议。 我System.Collections.IEnumerable, ICollection<KeyValuePair>, IEnumerable<KeyValuePair>, IDictionary是在实现System.Collections.IEnumerable, ICollection<KeyValuePair>, IEnumerable<KeyValuePair>, IDictionary

首先,从.NET集合类派生通常是不明智的,因为它们不为不从objectinheritance的调用提供虚方法。 在通过某个基类引用传递派生集合时,这可能会导致错误。 您最好实现IDictionary接口并在实现中聚合Dictionary<,> ,然后转发相应的调用。

除此之外,在您的具体情况下,您想要做的是:

 foreach( KeyValuePair pair in this ) { /* code here */ } 

base关键字主要用于访问基类的特定成员。 这不是你在这里做的 – 你试图迭代特定实例的项目……这只是this引用。

我同意JaredPar的评论,这不是一个好主意。 您可能不希望将Dictionary的所有方法公开暴露给外界,因此只需将Dictionary作为私有成员变量,然后为其提供自己的接口。

话虽如此,做你想做的事的方法是:

 foreach (KeyValuePair pair in this) 

Dictionary封装为自定义class MyDictionary的组合字段,并为class MyDictionary实现自定义IEnumerable和IEnumerator (或其变体)(或者创建一个实现方便的C# yield关键字以生成项目的方法)…

例如

 class MyDictionary : IEnumerable> { Dictionary _dict; IEnumerator> GetEnumerator() { return new MyEnum(this); // use your enumerator // OR simply forget your own implementation and return _dict.GetEnumerator(); } class MyEnum : IEnumerator> { internal MyEnum(MyDictionary dict) { //... dict } // implemented methods (.MoveNext, .Reset, .Current)... 

这保持了无关方法的封装。 你仍然可以从内部或外部迭代你的实例:

 // from outside MyDictionary mdict = new MyDictionary(); foreach (KeyValuePair kvp in mdict) //... // from inside, assuming: this == MyDictionary instance) public void MyDictionaryMethod() { foreach (KeyValuePair kvp in this) //...