相关疑难解决方法(0)

ValueType.GetHashCode的原生实现如何工作?

我创建了两个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)

c# hash struct

39
推荐指数
2
解决办法
6769
查看次数

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

我需要安排一种字典,其中键是一对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)

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

如何轻松搞定?

.net c# generics dictionary

6
推荐指数
3
解决办法
5768
查看次数

标签 统计

c# ×2

.net ×1

dictionary ×1

generics ×1

hash ×1

struct ×1