다음은 어떻게해야하고 열쇠를 해제를 재사용 :
internal class AutoKeyDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable
{
private readonly Dictionary<TKey, TValue> inner;
private readonly Func<TKey, TKey> incrementor;
private readonly Stack<TKey> freeKeys;
private readonly TKey keySeed;
private TKey currentKey;
public AutoKeyDictionary(TKey keySeed, Func<TKey, TKey> incrementor)
{
if (keySeed == null)
throw new ArgumentNullException("keySeed");
if (incrementor == null)
throw new ArgumentNullException("incrementor");
inner = new Dictionary<TKey, TValue>();
freeKeys = new Stack<TKey>();
currentKey = keySeed;
}
public TKey Add(TValue value) //returns the used key
{
TKey usedKey;
if (freeKeys.Count > 0)
{
usedKey = freeKeys.Pop();
inner.Add(usedKey, value);
}
else
{
usedKey = currentKey;
inner.Add(usedKey, value);
currentKey = incrementor(currentKey);
}
return usedKey;
}
public void Clear()
{
inner.Clear();
freeKeys.Clear();
currentKey = keySeed;
}
public bool Remove(TKey key)
{
if (inner.Remove(key))
{
if (inner.Count > 0)
{
freeKeys.Push(key);
}
else
{
freeKeys.Clear();
currentKey = keySeed;
}
return true;
}
return false;
}
public bool TryGetValue(TKey key, out TValue value) { return inner.TryGetValue(key, out value); }
public TValue this[TKey key] { get {return inner[key];} set{inner[key] = value;} }
public bool ContainsKey(TKey key) { return inner.ContainsKey(key); }
public bool ContainsValue(TValue value) { return inner.ContainsValue (value); }
public int Count { get{ return inner.Count; } }
public Dictionary<TKey,TValue>.KeyCollection Keys { get { return inner.Keys; } }
public Dictionary<TKey, TValue>.ValueCollection Values { get { return inner.Values; } }
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return inner.GetEnumerator(); }
IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)inner).GetEnumerator(); }
}
면책 조항 :이 코드를 테스트하지 않았습니다, 그것은 작은 중요성을 몇 pesty 버그가 수, 일반적인 접근 방식은 소리입니다.
앞서 설명한 방법으로 사전을 감싸는 클래스를 작성하십시오. 객체에서 키를 생성하는 방법을 알고 있다고 생각하십니까? –
키가 객체에서 생성되지는 않으며 키는 객체를 함께 연결하는 데 사용됩니다. 나는 각 키를 반복하고이 키가 0인지 확인하고 키 0이 존재하지 않으면 해당 키가있는 새 개체를 만들 것이다. 존재한다면 1,2,3,4에 대해 반복 할 것이다. 하지만 이것이 성능 문제를 일으킬 것이라는 것을 알았습니다. – None
새 키는 어떻게 생성됩니까? 그냥 자동으로 증가한다면'List'을 감쌀 수 있습니다. –
Lee