我创建了两个TheKey类型为k1 = {17,1375984}和k2 = {17,1593144}的结构.显而易见,第二个字段中的指针是不同的.但两者都得到相同的哈希码= 346948941.预计会看到不同的哈希码.请参阅下面的代码.
struct TheKey
{
public int id;
public string Name;
public TheKey(int id, string name)
{
this.id = id;
Name = name;
}
}
static void Main() {
// assign two different strings to avoid interning
var k1 = new TheKey(17, "abc");
var k2 = new TheKey(17, new string(new[] { 'a', 'b', 'c' }));
Dump(k1); // prints the layout of a structure
Dump(k2);
Console.WriteLine("hash1={0}", k1.GetHashCode());
Console.WriteLine("hash2={0}", k2.GetHashCode());
}
unsafe static void Dump<T>(T s) …Run Code Online (Sandbox Code Playgroud) 我需要安排一种字典,其中键是一对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)
这种方法需要字符串解析,还有很多额外的工作.
如何轻松搞定?