小编典典

多值字典

c#

如何在C#中创建多值字典?

例如Dictionary<T,T,T>,第一个T是键,其他两个是值。

所以这是可能的: Dictionary<int,object,double>

谢谢


阅读 456

收藏
2020-05-19

共1个答案

小编典典

只需创建一个Pair<TFirst, TSecond>类型并将其用作您的值即可。

我在C#中的Depth源代码中有一个示例。为简单起见,此处转载:

using System;
using System.Collections.Generic;

public sealed class Pair<TFirst, TSecond>
    : IEquatable<Pair<TFirst, TSecond>>
{
    private readonly TFirst first;
    private readonly TSecond second;

    public Pair(TFirst first, TSecond second)
    {
        this.first = first;
        this.second = second;
    }

    public TFirst First
    {
        get { return first; }
    }

    public TSecond Second
    {
        get { return second; }
    }

    public bool Equals(Pair<TFirst, TSecond> other)
    {
        if (other == null)
        {
            return false;
        }
        return EqualityComparer<TFirst>.Default.Equals(this.First, other.First) &&
               EqualityComparer<TSecond>.Default.Equals(this.Second, other.Second);
    }

    public override bool Equals(object o)
    {
        return Equals(o as Pair<TFirst, TSecond>);
    }

    public override int GetHashCode()
    {
        return EqualityComparer<TFirst>.Default.GetHashCode(first) * 37 +
               EqualityComparer<TSecond>.Default.GetHashCode(second);
    }
}
2020-05-19