c# - 从 KeyedCollection 添加和检索

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

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

最佳答案

你的 GetKeyForItem override 是指定项目键的内容。来自文档:

Unlike dictionaries, an element of KeyedCollection is not a key/value pair; instead, the entire element is the value and the key is embedded within the value. For example, an element of a collection derived from KeyedCollection<String,String> might be "John Doe Jr." where the value is "John Doe Jr." and the key is "Doe"; or a collection of employee records containing integer keys could be derived from KeyedCollection<int,Employee>. The abstractGetKeyForItem` method extracts the key from the element.

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

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

关于c# - 从 KeyedCollection 添加和检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3147396/

相关文章:

c# - 复制 KeyedCollection 的最快方法

c# - 强制调用基方法的虚方法模式

c# - Entity Framework :Why the collection type of entity class need to be instanced in the default constructor?

c# - GenericRepository 模式更新方法

c# - 无法将 JSON 值转换为 System.Nullable[System.Int32]

php - Eloquent 嵌套关系与 where 子句查询在错误条件下返回集合

c# - 从 KeyedCollection 获取键列表的最有效方法是什么?

php - 重新排序 Laravel 集合的优雅解决方案(或从一开始就完美地填充它)?

Scala Map vs HashMap

c# - KeyedCollection 是什么的集合?