有一个默认的IEqualityComparer的实现,它使用的ReferenceEquals?
Is there a default IEqualityComparer implementation that uses ReferenceEquals?
EqualityComparer< T> .DEFAULT
使用ObjectComparer,它使用的Object.Equals()。就我而言,对象已经实现了IEquatable,我需要忽略和只对象的引用进行比较。
EqualityComparer<T>.Default
uses ObjectComparer, which uses object.Equals(). In my case, the objects already implement IEquatable, which I need to ignore and compare by object's reference only.
谢谢!
以防万一没有默认的实现,这是我自己的:
Just in case there is no default implementation, this is my own:
编辑由280Z28:为什么要使用RuntimeHelpers.GetHash$c$c(object),其中有许多你可能以前从未见过的。 :)这个方法有两个作用,使其在正确的呼吁,这个实现:
Edit by 280Z28: Rationale for using RuntimeHelpers.GetHashCode(object)
, which many of you probably haven't seen before. :) This method has two effects that make it the correct call for this implementation:
的ReferenceEquals
适用于空参数,所以应该比较器的实施GetHash code()。
在它调用 Object.GetHash code()
非虚拟化。 的ReferenceEquals
具体忽略)的任何覆盖等于
,所以GetHash code(实施中应使用特殊的方法相匹配的ReferenceEquals的效果,而这正是RuntimeHelpers.GetHash code是。
It returns 0 when the object is null. Since ReferenceEquals
works for null parameters, so should the comparer's implementation of GetHashCode().
It calls Object.GetHashCode()
non-virtually. ReferenceEquals
specifically ignores any overrides of Equals
, so the implementation of GetHashCode() should use a special method that matches the effect of ReferenceEquals, which is exactly what RuntimeHelpers.GetHashCode is for.
[结束280Z28]
[end 280Z28]
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
/// <summary>
/// A generic object comparerer that would only use object's reference,
/// ignoring any <see cref="IEquatable{T}"/> or <see cref="object.Equals(object)"/> overrides.
/// </summary>
public class ObjectReferenceEqualityComparer<T> : EqualityComparer<T>
where T : class
{
private static IEqualityComparer<T> _defaultComparer;
public new static IEqualityComparer<T> Default
{
get { return _defaultComparer ?? (_defaultComparer = new ObjectReferenceEqualityComparer<T>()); }
}
#region IEqualityComparer<T> Members
public override bool Equals(T x, T y)
{
return ReferenceEquals(x, y);
}
public override int GetHashCode(T obj)
{
return RuntimeHelpers.GetHashCode(obj);
}
#endregion
}
上一篇:如何通过词典和变化值循环?词典
下一篇:SqlCommand.CommandTimeout和SqlConnection.ConnectionTimeout之间的区别是什么?区别、CommandTimeout、SqlCommand、Conne