C#继承Dictionary,迭代KeyValuePairs [英] C# inherit from Dictionary, iterate over KeyValuePairs

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

问题描述

我有一个继承自 Dictionary 的类.在实例方法中,我想遍历所有 KeyValuePair.我尝试执行以下操作:

foreach (KeyValuePair 基中的对)

但这失败并出现以下错误:

<块引用>

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

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

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

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

但是,我仍然想知道是否有办法通过 foreach 循环来做到这一点.

感谢关于不要从Dictionary继承的建议.我正在实现 System.Collections.IEnumerable, ICollection>, IEnumerable>, IDictionary.

解决方案

首先,从 .NET 集合类派生通常是不明智的,因为它们不为不是从 object.当通过某个基类引用传递派生集合时,这可能会导致错误.您最好实现 IDictionary 接口并在您的实现中聚合一个 Dictionary<,> - 然后将适当的调用转发到该接口.>

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

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

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

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

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

Edit: I found I can do the following:

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

However, I would still like to know if there's a way to do this via a foreach loop.

Edit: 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>.

解决方案

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#继承Dictionary,迭代KeyValuePairs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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