2014-02-18 2 views
3

데이터 개체의 속성에 키가 될 사전을 만드는 가장 쉬운 방법은 무엇입니까? 예 : 내가 가진 상상 :저장된 데이터의 속성을 키로 사용하는 사전

interface A 
{ 
    string Key{get;} 
    //other stuff 
} 

을 지금까지 나는이 : 같은를 달성하기 위해 더 좋은 방법은

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]; 
} 

있습니까? (콜렉션은 필요한 인덱서가있는 한 IDictionary를 구현할 필요가 없습니다.)

답변

5

당신은 KeyedCollection를 사용할 수 있습니다

public class MyCollection : KeyedCollection<string, A> 
{ 
    protected override GetKeyForItem(A a) 
    { 
     return a.Key; 
    } 
} 
+0

+1은 결코 하나가 존재 알고 있었다. –

관련 문제