我想创建一个实现BiDiDictionary<T1, T2>
和IDictionary<T1, T2>
的双向查找IDictionary<T2, T1>
:
class BiDiDictionary<T1, T2> : IDictionary<T1, T2>, IDictionary<T2, T1>
{
IDictionary<T1, T2> _t1t2 = new Dictionary<T1, T2>();
IDictionary<T2, T1> _t2t1 = new Dictionary<T2, T1>();
public void Add(T1 key, T2 value)
{
_t1t2.Add(key, value);
_t2t1.Add(value, key);
}
public bool ContainsKey(T1 key)
{
return _t1t2.ContainsKey(key);
}
public ICollection<T1> Keys
{
get { return _t1t2.Keys; }
}
public bool Remove(T1 key)
{
var t2 = _t1t2[key];
_t1t2.Remove(key);
_t2t1.Remove(t2);
}
public bool TryGetValue(T1 key, out T2 value)
{
return _t1t2.TryGetValue(key, out value);
}
public ICollection<T2> Values
{
get { return _t1t2.Values; }
}
public T2 this[T1 key]
{
get
{
return _t1t2[key];
}
set
{
_t1t2[key] = value;
_t2t1[value] = key;
}
}
public void Add(KeyValuePair<T1, T2> item)
{
Add(item.Key, item.Value);
}
public void Clear()
{
_t1t2.Clear();
_t2t1.Clear();
}
public bool Contains(KeyValuePair<T1, T2> item)
{
return _t1t2.Contains(item);
}
public void CopyTo(KeyValuePair<T1, T2>[] array, int arrayIndex)
{
_t1t2.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _t1t2.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(KeyValuePair<T1, T2> item)
{
Remove(item.Key);
}
public IEnumerator<KeyValuePair<T1, T2>> GetEnumerator()
{
return _t1t2.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add(T2 key, T1 value)
{
Add(value, key);
}
public bool ContainsKey(T2 key)
{
return _t2t1.ContainsKey(key);
}
ICollection<T2> IDictionary<T2, T1>.Keys
{
get { return _t2t1.Keys; }
}
public bool Remove(T2 key)
{
var t1 = _t2t1[key];
_t1t2.Remove(t1);
_t2t1.Remove(key);
}
public bool TryGetValue(T2 key, out T1 value)
{
return _t2t1.TryGetValue(key, out value);
}
ICollection<T1> IDictionary<T2, T1>.Values
{
get { return _t2t1.Values; }
}
public T1 this[T2 key]
{
get
{
return _t2t1[key];
}
set
{
this[value] = key;
}
}
public void Add(KeyValuePair<T2, T1> item)
{
Add(item.Key, item.Value);
}
public bool Contains(KeyValuePair<T2, T1> item)
{
return _t2t1.Contains(item);
}
public void CopyTo(KeyValuePair<T2, T1>[] array, int arrayIndex)
{
_t2t1.CopyTo(array, arrayIndex);
}
public bool Remove(KeyValuePair<T2, T1> item)
{
return Remove(item.Key);
}
IEnumerator<KeyValuePair<T2, T1>> IEnumerable<KeyValuePair<T2, T1>>.GetEnumerator()
{
return _t2t1.GetEnumerator();
}
}
但是,尝试编译它会导致以下错误:
BiDiDictionary<T1,T2>
无法实现Dictionary<T1,T2>
和Dictionary<T2,T1>
,因为它们可能会针对某些类型参数替换进行统一
有没有办法向编译器表明我已经意识到这个问题,并且只有在有人试图使用T1
和T2
的类时才会引发错误?< / p>