如何使用复合键进行字典?

Cap*_*mic 6 .net c# generics dictionary

我需要安排一种字典,其中键是一对enum和int,value是object.所以我想将一对映射到某个对象.

一种选择是

public enum SomeEnum
{
 value1, value2
}

class Key
{
  public SomeEnum;
  public int counter;  

  // Do I have to implement Compare here?
}

Dictionary<SomeEnum, object> _myDictionary;
Run Code Online (Sandbox Code Playgroud)

另一个选项是将enum和int转换为某个唯一键.

string key = String.Format("{0}/{1}", enumValue, intValue)
Run Code Online (Sandbox Code Playgroud)

这种方法需要字符串解析,还有很多额外的工作.

如何轻松搞定?

Onk*_*org 9

我会选择类似的东西

public enum SomeEnum
{
 value1, value2
}

public struct Key
{
  public SomeEnum;
  public int counter;  
}

Dictionary<Key, object>
Run Code Online (Sandbox Code Playgroud)

我想那会成功吗?


Rob*_*ine 8

如果您要将其放入字典中,那么您需要确保实现有意义的字典.Equals,.GetHashCode否则字典将无法正常运行.

我将从基本复合键的以下内容开始,然后实现自定义IComparer以获得所需的排序顺序.

public class MyKey
{
    private readonly SomeEnum enumeration;
    private readonly int number;

    public MyKey(SomeEnum enumeration, int number)
    {
        this.enumeration = enumeration;
        this.number = number;
    }

    public int Number
    {
        get { return number; }
    }

    public SomeEnum Enumeration
    {
        get { return enumeration; }
    }

    public override int GetHashCode()
    {
        int hash = 23 * 37 + this.enumeration.GetHashCode();
        hash = hash * 37 + this.number.GetHashCode();

        return hash;
    }

    public override bool Equals(object obj)
    {
        var supplied = obj as MyKey;
        if (supplied == null)
        {
            return false;
        }

        if (supplied.enumeration != this.enumeration)
        {
            return false;
        }

        if (supplied.number != this.number)
        {
            return false;
        }

        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • +1提及.Equals和GetHashCode陷阱.这是使用Tuple类型而不是滚动自己的简单键的一个很好的理由. (2认同)

Win*_*ith 7

如果您使用的是C#4.0,则可以使用Tuple类.

var key = Tuple.Create(SomeEnum.Value1, 3);
Run Code Online (Sandbox Code Playgroud)