我希望它在系统库中,但是很容易自己滚动。
下面,我将提供编写此类的框架,其用法如下:
var twoWayDict = new TwoWayDict();
twoWayDict["zero"] = 0;
// twoWayDict["zero"] == 0
// twoWayDict.Reverse[0] == "zero"
twoWayDict.Reverse[1] = "one";
// twoWayDict["one"] == 1
// twoWayDict.Reverse[1] == "one"
请记住,双向字典的一个关键点是,您应该期望所有输入都是紧密耦合的。换句话说,如果您重新使用一个键或一个值,您将删除先前链接的数据:
twoWayDict["zero"] = 0;
// Then later...
twoWayDict.Reverse[0] = "ZERO";
// Now twoWayDict["ZERO"] == 0
// Later still...
// Exception: Key not found! "zero" was dropped when you re-used value 0
Console.WriteLine(twoWayDict["zero"]);
最后,这里是一些示例代码。它是最小的-它应该作为任何想要充实自己版本的人的基础。注意,我实现了一个包装类,这样我就可以在不直接公开内部字典的情况下提供“reverse”属性。
// Generics note: K indicates "key" type and V indicates "value" type
using System.Collections.Generic;
namespace YourNamespaceHere.Collections
{
public class TwoWayDict
{
private Dictionary _dictKV;
private Dictionary _dictVK;
private ReverseDict _reverseDict;
public TwoWayDict()
{
_dictKV = new Dictionary();
_dictVK = new Dictionary();
_reverseDict = new ReverseDict(this);
}
public ReverseDict Reverse
{
get { return _reverseDict; }
}
// TwoWayDict[key] -> value
public V this[K key]
{
get { return _dictKV[key]; }
set
{
// Remove any existing key/value pair
Remove(key);
_dictKV[key] = value;
_dictVK[value] = key;
}
}
public void Remove(K key)
{
if (_dictKV.ContainsKey(key))
{
_dictVK.Remove(_dictKV[key]);
_dictKV.Remove(key);
}
}
// Wrapper that allows TwoWayDict to expose a convenient
// 'Reverse' property.
public class ReverseDict
{
private TwoWayDict _parent;
public ReverseDict(TwoWayDict parent)
{
_parent = parent;
}
public K this[V reverseKey]
{
get { return _parent._dictVK[reverseKey]; }
set { _parent[value] = reverseKey; }
}
public void Remove(V value)
{
if (_parent._dictVK.ContainsKey(value))
{
_parent.Remove(_parent._dictVK[value]);
}
}
}
}
}