ValueTuples是否适合用作字典键? [英] Are ValueTuples suitable as dictionary keys?

查看:75
本文介绍了ValueTuples是否适合用作字典键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这可能是一本便捷的字典:

I'm thinking this could be a convenient dictionary:

var myDict = new Dictionary<(int, int), bool>();

散列是什么样的?

等效的密钥类型是什么(

What would the hashes look like?
What would the equivalent key type (struct) look like?

推荐答案

是的,很好。 ValueTuple< ...> 家族是一组定义良好的规则结构,它们具有正确的相等性和哈希码行为,可以用作字典键。有一个轻微警告,它们是可变的而不是不可变的,但是由于存在复制语义,因此在这种情况下并不会真正影响它们(这意味着:在拥有密钥之后,您不能再更改密钥了。已添加,因为您只更改了键的不同副本;这与可变类作为键的问题非常不同)。您可以在此处查看代码

Yes, that's fine. The ValueTuple<...> family is a well-defined set of regular structs with the correct equality and hash-code behaviour to work as dictionary keys. There is a slight caveat in that they are mutable rather than immutable, but that doesn't really impact them in this context thanks to copy semantics (which means: you can't change the key after it has been added, as you're only changing a different copy of the key; this is very different to the problem with mutable classes as keys). You can see the code here.

这篇关于ValueTuples是否适合用作字典键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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