相关疑难解决方法(0)

为什么2个委托实例返回相同的哈希码?

请考虑以下事项:

  var x =  new Action(() => { Console.Write("") ; });
  var y = new Action(() => { });
  var a = x.GetHashCode();
  var b = y.GetHashCode();
  Console.WriteLine(a == b);
  Console.WriteLine(x == y);
Run Code Online (Sandbox Code Playgroud)

这将打印:

True
False
Run Code Online (Sandbox Code Playgroud)

为什么哈希码相同?

这有点令人惊讶,并且会使代表的使用Dictionary速度与a List(也就是O(n)查找)一样慢.

更新:

问题是为什么.IOW谁做出这样一个(愚蠢的)决定?

一个更好的哈希码实现应该是:

return Method ^ Target == null ? 0 : Target.GetHashcode();
// where Method is IntPtr
Run Code Online (Sandbox Code Playgroud)

.net c# delegates hashcode

31
推荐指数
1
解决办法
2433
查看次数

标签 统计

.net ×1

c# ×1

delegates ×1

hashcode ×1