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
循环执行此操作。
编辑:感谢有关不从Dictionary
inheritance的建议。 我System.Collections.IEnumerable, ICollection<KeyValuePair>, IEnumerable<KeyValuePair>, IDictionary
是在实现System.Collections.IEnumerable, ICollection<KeyValuePair>, IEnumerable<KeyValuePair>, IDictionary
。
首先,从.NET集合类派生通常是不明智的,因为它们不为不从object
inheritance的调用提供虚方法。 在通过某个基类引用传递派生集合时,这可能会导致错误。 您最好实现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)...
这保持了无关方法的封装。 你仍然可以从内部或外部迭代你的实例:
上述就是C#学习教程:C#inheritance自Dictionary,迭代KeyValuePairs分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
// 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) //...
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/991784.html