爲什麼使用兩個字典的自定義類型不起作用?雖然它會使用兩倍的內存,但它允許O(1)查找,並且應該按照您的要求工作。
然而,當涉及到通用參數,它可以變得有點毛。如果指定了相同的類型,這不是問題,但是如果指定了不同的類型,則索引器會中斷,因爲只能以單向方式獲取值。如果你重載索引,有兩個,即:
public K this[T value]
public T this[K value]
這將打破,如果你有相同的參數,因爲它不能夠解決。在這種情況下,我建議有兩個不同的類別:
public class TwoWayDictionary<T>
{
private Dictionary<T, T> _first;
private Dictionary<T, T> _second;
public TwoWayDictionary()
{
_first = new Dictionary<T, T>();
_second = new Dictionary<T, T>();
}
public void Add(T first, T second)
{
_first.Add(first, second);
_second.Add(second, first);
}
public T this[T value]
{
get
{
if(_first.ContainsKey(value))
{
return _first[value];
}
if(_second.ContainsKey(value))
{
return _second[value];
}
throw new ArgumentException(nameof(value));
}
}
}
和
public class TwoWayDictionary<T, K>
{
private readonly Dictionary<T, K> _first;
private readonly Dictionary<K, T> _second;
public TwoWayDictionary()
{
_first = new Dictionary<T, K>();
_second = new Dictionary<K, T>();
}
public void Add(T first, K second)
{
_first.Add(first, second);
_second.Add(second, first);
}
public K this[T value]
{
get
{
if (_first.ContainsKey(value))
{
return _first[value];
}
throw new ArgumentException(nameof(value));
}
}
public T this[K value]
{
get
{
if (_second.ContainsKey(value))
{
return _second[value];
}
throw new ArgumentException(nameof(value));
}
}
}
這將允許你使用它就像在評論中提到:
var dict = new TwoWayDictionary<string>();
dict.Add(".jpg", "image/jpg");
var mime = dict[".jpg"];
var ext = dict["image/jpg"];
,並指定2如果你想不同的類型:
var dict = new TwoWayDictionary<string, int>();
dict.Add(".jpg", 100);
var number = dict[".jpg"];
var ext = dict[100];
從理論上講,你需要'dictionary.Add(「.jpg」,「image/jpg」)'',並且可以將它用作var mime = dictionary [「。jpg」]''var var ext = dictionary [ 「圖像/ JPG」]'? –
@DaveZych正是! –
似乎有點毫無意義,因爲你仍然可以明確映射這些關係已經.. –