Why do 2 delegate instances return the same hashcode?

前端 未结 4 480
眼角桃花
眼角桃花 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:07

    Easy! Since here is the implementation of the GetHashCode (sitting on the base class Delegate):

    public override int GetHashCode()
    {
        return base.GetType().GetHashCode();
    }
    

    (sitting on the base class MulticastDelegate which will call above):

    public sealed override int GetHashCode()
    {
        if (this.IsUnmanagedFunctionPtr())
        {
            return ValueType.GetHashCodeOfPtr(base._methodPtr);
        }
        object[] objArray = this._invocationList as object[];
        if (objArray == null)
        {
            return base.GetHashCode();
        }
        int num = 0;
        for (int i = 0; i < ((int) this._invocationCount); i++)
        {
            num = (num * 0x21) + objArray[i].GetHashCode();
        }
        return num;
    }
    

    Using tools such as Reflector, we can see the code and it seems like the default implementation is as strange as we see above.

    The type value here will be Action. Hence the result above is correct.

    UPDATE

提交回复
热议问题