在C#中,Dictionary该类只接受一个键并将其映射到单个值.我正在寻找类似的东西,我可以传递一个有序的元组并获得一个值 - 而不是将它包装在一个类中.
这是我想要的一个非常假设的例子(使用按钮,而不是一些2D地图图块).目前,我可以这样做:
Dictionary<int, Button> buttons = new Dictionary<int, Button>();
Run Code Online (Sandbox Code Playgroud)
如果我想使用每个按钮的坐标作为键,我可以这样做:
Dictionary<Point, Button> buttons = new Dictionary<Point, Button>();
buttons[new Point(b.X, b.Y)] = b;
Run Code Online (Sandbox Code Playgroud)
我想做的是这个
Dictionary<int, int, Button> buttons = new Dictionary<int, int, Button>();
buttons[b.X, b.Y] = b;
Run Code Online (Sandbox Code Playgroud)
同样,这是一个简单的案例,有一个已知的解决方法.但我发现我不得不创建一个新的占位符类(struct?),其中包含我想用作关键字的每组参数.
这有点可能吗?
public class TupleDictionary<T1, T2, TValue> : Dictionary<Tuple<T1,T2>,TValue>
{
public TValue this[T1 t1, T2 t2]
{
get { return this[new Tuple<T1, T2>(t1, t2)]; }
set { this[new Tuple<T1, T2>(t1,t2)] = value; }
}
public void Add(T1 t1, T2 t2, TValue value)
{
Add(new Tuple<T1, T2>(t1, t2), value);
}
public void Remove(T1 t1, T2 t2)
{
Remove(new Tuple<T1, T2>(t1, t2));
}
public bool ContainsKey(T1 t1, T2 t2)
{
return ContainsKey(new Tuple<T1, T2>(t1, t2));
}
public bool TryGetValue(T1 t1, T2 t2, out TValue value)
{
return TryGetValue(new Tuple<T1, T2>(t1, t2), out value);
}
}
Run Code Online (Sandbox Code Playgroud)