首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从KeyedCollection添加和检索

从KeyedCollection添加和检索
EN

Stack Overflow用户
提问于 2010-06-30 15:59:18
回答 3查看 5K关注 0票数 3

我想使用KeyedCollection根据字符串键的值来存储一个类。我有以下代码:

代码语言:javascript
复制
public class MyClass
{
    public string Key;
    public string Test;
}

public class MyCollection : KeyedCollection<string, MyClass>
{
    public MyCollection() : base()
    {
    }

    protected override String GetKeyForItem(MyClass cls)
    {
        return cls.Key;
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyCollection col = new MyCollection();
        col.Add(new MyClass()); // Here is want to specify the string Key Value
    }
}

有人能告诉我我哪里做错了吗?我在哪里指定键值,以便我可以通过它进行检索?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-06-30 16:08:19

您的GetKeyForItem重写指定了项的键。从文档中:

与字典不同,KeyedCollection的元素不是键/值对;相反,整个元素就是值,而键嵌入在值中。例如,从KeyedCollection<String,String>派生的集合的元素可能是"John Doe Jr“。其中的值是"John Doe Jr.“关键字是"Doe";或者包含整数关键字的雇员记录的集合可以从KeyedCollection<int,Employee>. The abstract的GetKeyForItem`方法中提取关键字。

因此,为了正确设置该项的键值,应在将其添加到集合之前设置其Key属性:

代码语言:javascript
复制
MyCollection col = new MyCollection();
MyClass myClass = new MyClass();
myClass.Key = "This is the key for this object";
col.Add(myClass); 
票数 8
EN

Stack Overflow用户

发布于 2010-06-30 16:07:19

KeyedCollection是一个用于创建键值集合的基类,因此您需要自己实现很多东西。

也许使用Dictionary会更容易、更快。

票数 1
EN

Stack Overflow用户

发布于 2010-06-30 16:33:10

我知道这有点不同,但是你有没有考虑过实现一个indexer

代码语言:javascript
复制
public string this[string index]
{
    get { 
      // put get code here
    }
    set {
      // put set code here.
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3147396

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档