为了账号安全,请及时绑定邮箱和手机立即绑定

在IEqualityComparer中包装委托

在IEqualityComparer中包装委托

慕雪6442864 2019-09-19 09:42:45
几个Linq.Enumerable函数需要一个IEqualityComparer<T>。是否有一个方便的包装类适应delegate(T,T)=>bool实现IEqualityComparer<T>?编写一个很容易(如果你忽略了定义正确的哈希码的问题),但我想知道是否有开箱即用的解决方案。具体来说,我想对Dictionarys 进行集合操作,仅使用Keys来定义成员资格(同时根据不同的规则保留值)。
查看完整描述

3 回答

?
婷婷同学_

TA贡献1844条经验 获得超8个赞

以下是我对[IMNSHO]关键修复默认的散列策略: -


class FuncEqualityComparer<T> : IEqualityComparer<T>

{

    readonly Func<T, T, bool> _comparer;

    readonly Func<T, int> _hash;


    public FuncEqualityComparer( Func<T, T, bool> comparer )

        : this( comparer, t => 0 ) // NB Cannot assume anything about how e.g., t.GetHashCode() interacts with the comparer's behavior

    {

    }


    public FuncEqualityComparer( Func<T, T, bool> comparer, Func<T, int> hash )

    {

        _comparer = comparer;

        _hash = hash;

    }


    public bool Equals( T x, T y )

    {

        return _comparer( x, y );

    }


    public int GetHashCode( T obj )

    {

        return _hash( obj );

    }

}


查看完整回答
反对 回复 2019-09-19
  • 3 回答
  • 0 关注
  • 373 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信