Why do 2 delegate instances return the same hashcode?

前端 未结 4 479
眼角桃花
眼角桃花 2021-01-31 16:55

Take the following:

  var x =  new Action(() => { Console.Write(\"\") ; });
  var y = new Action(() => { });
  var a = x.GetHashCode();
  var b = y.GetHash         


        
4条回答
  •  日久生厌
    2021-01-31 17:02

    From MSDN :

    The default implementation of GetHashCode does not guarantee uniqueness or consistency; therefore, it must not be used as a unique object identifier for hashing purposes. Derived classes must override GetHashCode with an implementation that returns a unique hash code. For best results, the hash code must be based on the value of an instance field or property, instead of a static field or property.

    So if you have not overwritten the GetHashCode method, it may return the same. I suspect this is because it generates it from the definition, not the instance.

提交回复
热议问题