Enumerable.SequenceEqual和 EqualityComparer
来自 MSDN
的 SequenceEqual(IEnumerable, IEnumerable) 方法 枚举两个源序列 并行并比较相应的 使用默认相等的元素 TSource 的比较器,默认。这 默认相等比较器,Default,是 用于比较类型的值 实施 IEqualityComparer 通用 界面。
a) 据我理解上面的引用,它暗示 EqualityComparer
用于比较实现 IEqualityComparer
的类型的元素,而实际上Default
用于返回 IEqualityComparer
的特定实现,该实现可以调用IEquatable
(假设 T
可分配给 IEquatable
)或者调用 Object.Equals
>
b) 引用还表明 TSource
必须实现 IEqualityComparer
,这是不正确的:
static void Main(string[] args)
{
Test test1 = new Test();
Test test2 = new Test();
Test[] list1 = { test1, test2 };
Test[] list2 = { test1, test2 };
bool eq = list1.SequenceEqual(list2); //works
}
public class Test { }
那么我是否误解了引用的意图传达还是引用完全错误?
谢谢
From MSDN
The
SequenceEqual(IEnumerable,
IEnumerable) method
enumerates the two source sequences in
parallel and compares corresponding
elements by using the default equality
comparer for TSource, Default. The
default equality comparer, Default, is
used to compare values of the types
that implement the
IEqualityComparer generic
interface.
a) As I understand the above quote, it's implying that EqualityComparer<T>.Default
is used to compare elements of types that implement the IEqualityComparer<T>
, when in fact Default
is used to return a particular implementation of IEqualityComparer<T>
that either calls IEquatable<T>.Equals
(assuming T
is assignable to IEquatable<T>
) or it calls Object.Equals
b) Quote also suggests that TSource
must implement IEqualityComparer<T>
, which isn't true:
static void Main(string[] args)
{
Test test1 = new Test();
Test test2 = new Test();
Test[] list1 = { test1, test2 };
Test[] list2 = { test1, test2 };
bool eq = list1.SequenceEqual(list2); //works
}
public class Test { }
So did I misinterpret what the quote is trying to convey or is the quote plain wrong?
thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不是
TSource
应该实现IEqualityComparer
,而是
EqualityComparer.Default
实现IEqualityComparer
这太容易被忽视了,不值得提及。
Not
TSource
should implementIEqualityComparer
But
EqualityComparer<T>.Default
implementsIEqualityComparer
That's too oblivious to be mentioned.
来自 MSDN:
在您的示例中,它仅使用引用相等性,这是引用对象的默认相等性实现。
From MSDN:
In your example case it just uses reference equality which is the default equality implementation for reference objects.