字典键入存储数据的属性

Grz*_*nio 3 .net c# dictionary

创建将键入数据对象属性的字典的最简单方法是什么?想象我有:

interface A
{
  string Key{get;}
  //other stuff
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我有:

IDictionary<string, A> dict = new Dictionary<string, A>();
void Add(A a)
{
  dict[a.Key] = a; //I would prefer that the collection class managed this relationship
}

A Get(string key)
{
  return dict[key];
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来实现同样的目标?(该集合不需要实现IDictionary,只要它具有所需的索引器).

Lee*_*Lee 5

你可以使用KeyedCollection:

public class MyCollection : KeyedCollection<string, A>
{
    protected override GetKeyForItem(A a)
    {
        return a.Key;
    }
}
Run Code Online (Sandbox Code Playgroud)