什么时候使用元组和KeyValuePair更好? [英] When is it better to use a Tuple versus a KeyValuePair?

查看:31
本文介绍了什么时候使用元组和KeyValuePair更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我拥有与数据对相关的数据时,我通常会使用 KeyValuePair< TKey,TValue> 类型,从某种意义上说,一个是另一个的密钥.如果数据不相关,则 Tuple< T1,T2> 类型更有意义,我会考虑.

I've generally used the KeyValuePair<TKey,TValue> type whenever I have data that is pair-related in the sense that one is a key to the other. If the data is unrelated then the Tuple<T1,T2> type makes more sense and I'd go with that.

现在,我只阅读了这篇文章关于为何通常避免 KeyValuePair< TKey,TValue> 的文章>,并且更喜欢 Tuple< T1,T2> .主要参数是 Tuple< T1,T2> 的性能优势.

Now I just read this article about why to generally avoid KeyValuePair<TKey,TValue> and prefer Tuple<T1,T2>. The primary argument being the performance benefit of Tuple<T1,T2>.

除了性能之外,还有什么理由比 Tuple< T1,T2> 是KVP更好的选择吗?

Outside performance, is there any reason a KVP would be a better choice than a Tuple<T1,T2>?

推荐答案

好吧,可以认为该类型的命名不正确.名为KeyValuePair的名称应表示一个键和一个值.如果您的两个对象实际上不是键和值,而仅仅是两件事怎么办?如果我看到的方法或属性的类型为 KeyValuePair< TKey,TValue> ,则我希望KVP的值是一个键和一个值.这实际上仅是传达意图并在将来向自己或其他团队成员明确说明的问题.元组并不表示这种关联.

Well, the type could be considered poorly named, for one. A KeyValuePair as named should represent a key and a value. What if your two objects aren't really a key and a value, just two things? If I were to see a method or property that had a type of KeyValuePair<TKey, TValue>, I would expect the values of the KVP to be a key and a value. This is really just a matter of communicating intention and making it clear to yourself in the future, or possibly other team members. A tuple does not indicate that kind of association.

Tuples还使添加另一个值变得更容易,使它成为3元组(或三元组,不过您想调用它).某些.NET语言(例如F#),在元组周围也具有特殊的语法

Tuples also make it easier to add another value, making it a 3-tuple (or a triplet, however you want to call it). Some .NET languages, like F#, have special syntax around tuples as well.

从实现角度来看, Tuple 做很多事情, KeyValuePair 做不到.元组具有可比性,它们实现了 IComparable IStructuralEquatable 接口,因此可以轻松比较两个元组.

For an implementation perspective, Tuple does many things KeyValuePair does not. Tuples are comparable, they implement the IComparable and IStructuralEquatable interfaces, so it makes it easier to compare two tuples.

这篇关于什么时候使用元组和KeyValuePair更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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