添加和检索KeyedCollection

Pau*_*els 3 c# collections keyedcollection

我想使用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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Aak*_*shM 8

您的GetKeyForItem覆盖是指定项目的键的内容.来自文档:

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

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

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