When is it better to use a Tuple versus a KeyValuePair?

前端 未结 4 1248
臣服心动
臣服心动 2021-02-01 11:49

I\'ve generally used the KeyValuePair type whenever I have data that is pair-related in the sense that one is a key to the other. If the data is

4条回答
  •  面向向阳花
    2021-02-01 12:21

    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, 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 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.

    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.

提交回复
热议问题