如何使用复合键进行字典?
我需要安排一种字典,其中键是一对枚举和int,值是对象。 所以我想将一对映射到某个对象。
一种选择是
public enum SomeEnum { value1, value2 } class Key { public SomeEnum; public int counter; // Do I have to implement Compare here? } Dictionary _myDictionary;
另一个选项是将enum和int转换为某个唯一键。
string key = String.Format("{0}/{1}", enumValue, intValue)
这种方法需要字符串解析,还有很多额外的工作。
如何轻松搞定?
我会选择类似的东西
public enum SomeEnum { value1, value2 } public struct Key { public SomeEnum; public int counter; } Dictionary
我想那会成功吗?
如果您要将它放在字典中,那么您需要确保实现有意义的.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; } }
如果您使用的是C#4.0,则可以使用Tuple类。
var key = Tuple.Create(SomeEnum.Value1, 3);