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

编程入门 行业动态 更新时间:2024-10-19 12:45:15
本文介绍了在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#中检查值元组是否相等的正确方法?

本文发布于:2023-11-29 17:10:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647049.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确   方法   值元组

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!