Why do 2 delegate instances return the same hashcode?

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

    My first attempt of a better implementation:

    public class DelegateEqualityComparer:IEqualityComparer
    {
        public bool Equals(Delegate del1,Delegate del2)
        {
            return (del1 != null) && del1.Equals(del2);
        }
    
        public int GetHashCode(Delegate obj)
        {
                if(obj==null)
                    return 0;
                int result = obj.Method.GetHashCode() ^ obj.GetType().GetHashCode();
                if(obj.Target != null)
                    result ^= RuntimeHelpers.GetHashCode(obj);
                return result;
        }
    }
    

    The quality of this should be good for single cast delegates, but not so much for multicast delegates (If I recall correctly Target/Method return the values of the last element delegate).

    But I'm not really sure if it fulfills the contract in all corner cases.

    Hmm it looks like quality requires referential equality of the targets.

提交回复
热议问题