我想使用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
}
}有人能告诉我我哪里做错了吗?我在哪里指定键值,以便我可以通过它进行检索?
发布于 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属性:
MyCollection col = new MyCollection();
MyClass myClass = new MyClass();
myClass.Key = "This is the key for this object";
col.Add(myClass); 发布于 2010-06-30 16:07:19
KeyedCollection是一个用于创建键值集合的基类,因此您需要自己实现很多东西。
也许使用Dictionary会更容易、更快。
发布于 2010-06-30 16:33:10
我知道这有点不同,但是你有没有考虑过实现一个indexer。
public string this[string index]
{
get {
// put get code here
}
set {
// put set code here.
}
}https://stackoverflow.com/questions/3147396
复制相似问题