且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#中检查值元组是否相等的正确方法?

更新时间:2023-11-29 08:25:22

在C#7.3之前,您有两种选择:使用.等于,或者可以写出 == 比较,对于本身支持 == :

Prior to C# 7.3, you had two choices: use .Equals, or you can write out the == comparison long-hand, for elements that themselves support ==:

(a, b).Equals((c, d)) // true if a.Equals(c) && b.Equals(d)

a == c && b == d // works if the types support ==

(有关以下内容的详细信息 Equals()的工作原理,请查看源代码.)

(For details of how Equals() works, check out the source.)

从C#7.3开始,对 == 的直接支持已添加到值元组:

As of C# 7.3, direct support for == has been added to value tuples:

(a, b) == (c, d) // compiler converts to a == c && b == d

请注意,这里的 == 不是元组类型定义的运算符.这是一个编译技巧",它(对于嵌套元组)递归地对每个元素执行 == .结果,仅当元素本身支持 == 时,才可以使用此技术.结果,这种方法不适用于泛型,除非限于确实支持 == 的类型.因此,以下代码将无法编译:

Note that == here is not an operator defined by the tuple types. It's a "compiler trick" that recursively (for nested tuples) performs == on each of the elements. As a result, this technique can only be used if the elements support == themselves. As a result, this approach does not work for generics, unless constrained to types that do support ==. So the following code will not compile:

public bool Compare<T1, T2>((T1 a, T2 b) x, (T1 a, T2 b) y) => x == y