出于内部目的,我写了一个BiDictionary。它不是防弹的,因为我不会将它暴露给用户,所以它对我来说很好用。它让我可以根据需要获取任一密钥。
KeyPair<,> 是实现IEnumerable<,> 和Add 方法所必需的,这样我们才能使用对象初始化器。
internal class KeyPair<TKey1, TKey2>
{
public TKey1 Key1 { get; set; }
public TKey2 Key2 { get; set; }
}
这是作为动态对象的主类,因此我们可以在检索值时在其上使用键名:
internal class BiDictionary<TKey1, TKey2> : DynamicObject, IEnumerable<KeyPair<TKey1, TKey2>>
{
private readonly Dictionary<TKey1, TKey2> _K1K2 = new Dictionary<TKey1, TKey2>();
private readonly Dictionary<TKey2, TKey1> _K2K1 = new Dictionary<TKey2, TKey1>();
private readonly string _key1Name;
private readonly string _key2Name;
public BiDictionary(string key1Name, string key2Name)
{
_key1Name = key1Name;
_key2Name = key2Name;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (binder.Name == _key1Name)
{
result = _K1K2;
return true;
}
if (binder.Name == _key2Name)
{
result = _K2K1;
return true;
}
result = null;
return false;
}
public void Add(TKey1 key1, TKey2 key2)
{
_K1K2.Add(key1, key2);
_K2K1.Add(key2, key1);
}
public IEnumerator<KeyPair<TKey1, TKey2>> GetEnumerator()
{
return _K1K2.Zip(_K2K1, (d1, d2) => new KeyPair<TKey1, TKey2>
{
Key1 = d1.Key,
Key2 = d2.Key
}).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
例子:
dynamic bidic = new BiDictionary<string, string>("Key1", "Key2")
{
{ "foo", "bar" },
{ "baz", "qux" }
};
var bar = bidic.Key1["foo"];
var foo = bidic.Key2["bar"];
如果您在外面修改任何字典,它们可能会不同步。为此,我使用ObservableDictionary,以便在其中一个发生更改时更新另一个,但为了简单起见,我删除了这部分代码以演示主要逻辑。