0

这是我的问题:我似乎无法使用 .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;
            }
*/
        }
    }
}

资料来源:

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

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

4

2 回答 2

2

此类集合通常旨在通过知道密钥来实现项目的快速访问时间:检索与给定项目关联的密钥有点奇怪,因为它可能会引发模棱两可的情况。实际上,您尝试覆盖的方法具有受保护的修饰符这一事实强调了它不应该从“外部”访问。

举个例子:你可以存储同一个对象两次,但使用不同的键,你的方法将不知道选择哪个键。

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

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

一个解决方案可能是实现该方法并通过您需要创建的其他新方法公开其结果,该方法可以访问 GetKeyForItem,例如:

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

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

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

MyKeyedCollection keyd = new MyKeyedCollection();

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

int keys = keyd.Dictionary.Keys;
于 2018-04-15T23:31:59.110 回答
2

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

有关关键字,请参阅 文档。protected

由于类程序不是从 KeyedCollection 派生的,它不能访问方法 GetKeyForItem

于 2018-04-15T23:22:29.863 回答