元组(或数组)作为C#中的字典键

元组(或数组)作为C#中的字典键,第1张

元组(或数组)作为C#中的字典键

如果您使用的是.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);    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5084781.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存