我正在尝试用 C# 制作字典查找表。我需要将 3 元组值解析为一个字符串。我尝试使用数组作为键,但这没有用,我不知道还能做什么。在这一点上,我正在考虑制作一个字典的字典,但看起来可能不是很漂亮,尽管这是我在 javascript 中的做法。
最佳答案
如果您使用的是 .NET 4.0,请使用元组:
lookup = new Dictionary<Tuple<TypeA, TypeB, TypeC>, string>();
如果没有,您可以定义一个 Tuple
并将其用作键。元组需要覆盖 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);
}
}
关于c# - 元组(或数组)作为 C# 中的字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/955982/