在C#中检查值元组是否相等的正确方法? [英] Correct way to check value tuples for equality in C#?

查看:39
本文介绍了在C#中检查值元组是否相等的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出两个(int,int)类型的变量,如何检查它们是否表示相等的值?

Given two variables of type (int, int), how do I check if they represent equal values?

例如:

var a = (1, 2);
var b = (1, 2);

var c = a == b; // Error CS0019 Operator '==' cannot be applied to operands
                // of type '(int, int)' and '(int, int)'

在C#7中如何进行此比较?我应该使用 .Equals 还是其他方式?

How is this comparison meant to be done in C# 7? Should I use .Equals instead or do it some other way?

推荐答案

在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

这篇关于在C#中检查值元组是否相等的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆