Wrap a delegate in an IEqualityComparer(在 IEqualityComparer 中包装委托)
问题描述
几个 Linq.Enumerable 函数采用 IEqualityComparer<T>
.是否有一个方便的包装类来适应 delegate(T,T)=>bool
来实现 IEqualityComparer<T>
?编写一个很容易(如果您忽略了定义正确哈希码的问题),但我想知道是否有开箱即用的解决方案.
Several Linq.Enumerable functions take an IEqualityComparer<T>
. Is there a convenient wrapper class that adapts a delegate(T,T)=>bool
to implement IEqualityComparer<T>
? It's easy enough to write one (if your ignore problems with defining a correct hashcode), but I'd like to know if there is an out-of-the-box solution.
具体来说,我想对 Dictionary
进行设置操作,只使用 Keys 来定义成员资格(同时根据不同的规则保留值).
Specifically, I want to do set operations on Dictionary
s, using only the Keys to define membership (while retaining the values according to different rules).
推荐答案
通常情况下,我会通过在答案上评论 @Sam 来解决这个问题(我已经对原始帖子进行了一些编辑,以便在没有改变行为.)
Ordinarily, I'd get this resolved by commenting @Sam on the answer (I've done some editing on the original post to clean it up a bit without altering the behavior.)
以下是我的 @Sam 的回答的即兴演奏, 对默认散列策略进行了 [IMNSHO] 关键修复:-
The following is my riff of @Sam's answer, with a [IMNSHO] critical fix to the default hashing policy:-
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 );
}
}
这篇关于在 IEqualityComparer 中包装委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 IEqualityComparer 中包装委托


基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01