C#从字典继承,遍历KeyValuePairs [英] C# inherit from Dictionary, iterate over KeyValuePairs

查看:1372
本文介绍了C#从字典继承,遍历KeyValuePairs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类从继承字典<字符串,字符串> 。在实例方法,我想遍历所有 KeyValuePair<字符串,字符串> 的。我试着做以下几点:

I have a class that inherits from Dictionary<string, string>. Within an instance method, I want to iterate over all KeyValuePair<string, string>'s. I've tried doing the following:

foreach (KeyValuePair<string, string> pair in base)

但这种失败,出现以下错误:

But this fails with the following error:

关键字'基地'的使用无效在这种情况下

Use of keyword 'base' is not valid in this context

我怎么能遍历 KeyValuePair&LT;字符串,字符串&GT; 的一个实例方法,从派生的类字典&LT;字符串,字符串&GT;

How can I iterate over the KeyValuePair<string, string>'s in an instance method in a class that derives from Dictionary<string, string>?

编辑:我发现我能做到以下几点:

I found I can do the following:

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

不过,我还是想知道,如果有一种方法通过的foreach 循环来做到这一点。

编辑:感谢约不是从词典&LT继承了意见;字符串,字符串&GT; 。我代替实施 System.Collections.IEnumerable,ICollection的&LT; KeyValuePair&LT;字符串,字符串&GT;&gt;中的IEnumerable&LT; KeyValuePair&LT;字符串,字符串&GT;&gt;中的IDictionary&LT;字符串,字符串&GT;

thanks for the advice about not inheriting from Dictionary<string, string>. I'm instead implementing System.Collections.IEnumerable, ICollection<KeyValuePair<string, string>>, IEnumerable<KeyValuePair<string, string>>, IDictionary<string, string>.

推荐答案

首先,从.NET集合类派生一般是不明智的,因为他们不提供没有从继承调用虚拟方法对象。通过一个基类的引用传递派生集合时某处这可能会导致错误。你最好还是实施的IDictionary&LT; T,TKEY的&GT; 接口和聚合一个词典&LT;,&GT; 你里面执行 - 为你再往前适当的调用

First, deriving from the .NET collection classes is generally ill-advised because they don't offer virtual methods for calls not inherited from object. This can result in bugs when passing your derived collection in via a base-class reference somewhere. You are better off implementing the IDictionary<T,TKey> interface and aggregating a Dictionary<,> inside your implementation - to which you then forward the appropriate calls.

除此之外,在特定的情况下,你想要做的是:

That aside, in your specific case, what you want to do is:

foreach( KeyValuePair<string,string> pair in this )  { /* code here */ }

关键字主要是用来访问你的基类的特定成员。这不是你在这里做什么 - 你正试图遍历特定实例的物品......这简直是在这个引用

The base keyword is primarily used to access specific members of your base class. That's not what you're doing here - you are attempting to iterate over the items of a particular instance ... which is simply the this reference.

这篇关于C#从字典继承,遍历KeyValuePairs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆