这是我的问题:我似乎无法使用 .Dictionary 属性或 GetKeyForItem 方法。是否有我缺少的 using 语句或其他内容?本质上,我想为我的 keyedcollection 中的每个对象检索一个键列表。我找到了另一种方法(如代码所示),但我只是想知道为什么内置的 .Dictionary 和 .GetKeyForItem 不起作用。我在想,如果我无法访问这些,也许我设置不正确?谢谢您的帮助。
namespace testList
{
public class MyData //data itself has to contain the key.
{
public int Id;
public List<string> Data;
}
public class MyKeyedCollection : KeyedCollection<int, MyData>
{
//was initially protected. Changed to public. Still can't access this?
public override int GetKeyForItem(MyData item)
{
return item.Id;
}
}
class Program
{
static void Main(string[] args)
{
MyData nd = new MyData();
MyData md = new MyData();
nd.Id = 2;
nd.Data = new List<string>();
nd.Data.Add("Random Item");
md.Id =1;
md.Data = new List<string>();
md.Data.Add("First Item");
md.Data.Add("Second item");
KeyedCollection<int, MyData> keyd = new MyKeyedCollection();
keyd.Add(nd);
keyd.Add(md);
// doesn't recognize keyd.GetKeyForItem
//Since the mentioned methods aren't working, my only other solution is this:
/*
int[] keys = new int[keyd.Count];
for(int i=0; i<keyd.Count; i++)
{
keys[i] = keyd[i].Id;
}
*/
}
}
}
资料来源: