我试图在C#中创建一个字典查找表。我需要将三元组的值解析为一个字符串。我尝试使用数组作为键,但是那没有用,而且我不知道该怎么办。在这一点上,我正在考虑制作“字典词典”,尽管我将使用javascript做到这一点,但看起来可能不太漂亮。
如果您使用的是.NET 4.0,请使用元组:
lookup = new Dictionary<Tuple<TypeA, TypeB, TypeC>, string>();
如果不是,则可以定义一个元组并将其用作键。元组需要重写GetHashCode,Equals和IEquatable:
struct Tuple<T, U, W> : IEquatable<Tuple<T,U,W>> { readonly T first; readonly U second; readonly W third; public Tuple(T first, U second, W third) { this.first = first; this.second = second; this.third = third; } public T First { get { return first; } } public U Second { get { return second; } } public W Third { get { return third; } } public override int GetHashCode() { return first.GetHashCode() ^ second.GetHashCode() ^ third.GetHashCode(); } public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) { return false; } return Equals((Tuple<T, U, W>)obj); } public bool Equals(Tuple<T, U, W> other) { return other.first.Equals(first) && other.second.Equals(second) && other.third.Equals(third); } }