【问题标题】:Adding and retrieving from a KeyedCollection从 KeyedCollection 添加和检索
【发布时间】:2011-03-10 00:15:27
【问题描述】:

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

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
    }
}

谁能告诉我我在这里做错了什么?我在哪里指定键值以便我可以通过它检索?

【问题讨论】:

    标签: c# collections keyedcollection


    【解决方案1】:

    您的GetKeyForItem 覆盖指定了项目的密钥。来自文档:

    与字典不同,KeyedCollection 的元素不是键/值对;相反,整个元素是值,键嵌入在值中。例如,从KeyedCollection&lt;String,String&gt; 派生的集合元素可能是“John Doe Jr”。其中值为“John Doe Jr”。关键是“Doe”;或者包含整数键的员工记录集合可以从KeyedCollection&lt;int,Employee&gt;. The abstractGetKeyForItem`方法从元素中提取键。

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

    MyCollection col = new MyCollection();
    MyClass myClass = new MyClass();
    myClass.Key = "This is the key for this object";
    col.Add(myClass); 
    

    【讨论】:

    • +1 - 用于研究和回答问题,而不是简单地说“使用字典” - 这可能是我想说的。
    【解决方案2】:

    KeyedCollection 是用于创建键控集合的基类,因此您需要自己实现很多内容。

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

    【讨论】:

    • 虽然通用字典是首选方法; KeyedCollections 允许您将对象加载到集合中,其中对象中的成员是集合值的键。
    【解决方案3】:

    我知道它略有不同,但您是否考虑过实施indexer

    public string this[string index]
    {
        get { 
          // put get code here
        }
        set {
          // put set code here.
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 2013-06-21
      • 2011-12-02
      • 1970-01-01
      相关资源
      最近更新 更多