我想按以下方式将单词存储在字典中:
我可以按单词获取单词代码:dict["SomeWord"]
-> 123
并逐字获取代码:dict[123]
-> "SomeWord"
这是真的吗?当然,一种方法是使用两部词典:Dictionary<string,int>
和 Dictionary<int,string>
但是还有别的办法吗?
最佳答案
我快速编写了几个类,让您可以做您想做的事。您可能需要使用更多功能来扩展它,但这是一个很好的起点。
代码的使用如下所示:
var map = new Map<int, string>();
map.Add(42, "Hello");
Console.WriteLine(map.Forward[42]);
// Outputs "Hello"
Console.WriteLine(map.Reverse["Hello"]);
//Outputs 42
定义如下:
public class Map<T1, T2>
{
private Dictionary<T1, T2> _forward = new Dictionary<T1, T2>();
private Dictionary<T2, T1> _reverse = new Dictionary<T2, T1>();
public Map()
{
this.Forward = new Indexer<T1, T2>(_forward);
this.Reverse = new Indexer<T2, T1>(_reverse);
}
public class Indexer<T3, T4>
{
private Dictionary<T3, T4> _dictionary;
public Indexer(Dictionary<T3, T4> dictionary)
{
_dictionary = dictionary;
}
public T4 this[T3 index]
{
get { return _dictionary[index]; }
set { _dictionary[index] = value; }
}
}
public void Add(T1 t1, T2 t2)
{
_forward.Add(t1, t2);
_reverse.Add(t2, t1);
}
public Indexer<T1, T2> Forward { get; private set; }
public Indexer<T2, T1> Reverse { get; private set; }
}
关于c# - C# 中的双向/双向字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10966331/