KeyedCollection GetKeyForItem 和字典不起作用

KeyedCollection GetKeyForItem and Dictionary not working

这是我的问题:我似乎无法使用 .Dictionary 属性 或 GetKeyForItem 方法。是否有我缺少的使用声明或其他内容?本质上,我想为我的 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;
            }
*/
        }
    }
}

来源:

http://geekswithblogs.net/NewThingsILearned/archive/2010/01/07/using-keyedcollectionlttkey-titemgt.aspx

https://msdn.microsoft.com/en-us/library/ms132438.aspx

protected 关键字是成员访问修饰符。受保护成员可在其 class 内和派生的 class 实例中访问。

protected 关键字参见 documentation

由于 Class 程序不是从 KeyedCollection 派生的,因此它无法访问方法 GetKeyForItem

此类 collection 通常旨在通过知道密钥来快速访问您的项目:检索与给定项目关联的密钥有点奇怪,因为它可能会出现模棱两可的情况. 实际上,您尝试覆盖的方法具有 protected 修饰符这一事实强调它不应从 "outside".

访问

例如:您可以将相同的 object 存储两次,但使用不同的密钥,您的方法将不知道要选择哪个密钥。

这就是说,根据您的需要,您正在寻找的解决方案可能会有所不同。

无论如何,回答你的问题: collection 的静态类型是 KeyedCollection,因此在编译时您看不到 GetKeyForItem 方法,因为它是受保护的。 此外,不允许覆盖 C# 中方法的访问修饰符,如 here.

所述

解决方案可能是通过您需要创建的附加新方法实现该方法并公开其结果,该方法将有权访问 GetKeyForItem,例如:

protected override int GetKeyForItem(MyData item) {
    return item.Id;
}

public int MyGetKeyForItem(MyData item) {
    return GetKeyForItem(item);
}

您的 collection 然后需要按如下方式初始化才能访问 MyGetKeyForItem 方法:

MyKeyedCollection keyd = new MyKeyedCollection();

然后,如果您需要检索 collection 中定义的所有键,您可以先将其作为 IDictionary 获取,然后检索所有键:

int keys = keyd.Dictionary.Keys;