字典是否可以将数组作为键? [英] Whether a Dictionary can have Array as Key?

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

问题描述

Am在字典中遇到问题. 数组是否可以是值的键??

Am Facing a problem in Dictionaries. Whether an Array can be a Key of a Value???

Dictionary<string[], int> di = new Dictionary<string[], int>();
di.Add(new string[]
{
    "1","2"
}, 1);

di.Add(new string[]
{
    "2","3"
}, 2);

MessageBox.Show(di[new string[] { "2", "3" }].ToString()); // Here KeyNotFoundException occurred.

为什么要例外?

推荐答案

默认情况下,仅比较数组的引用,因此您要么必须

By default only references of the arrays would be compared, so you either have to

  1. 提供自定义 IEqualityComparer<string[]>
  2. 使用 Tuple<string, string> 作为键(因为您只有两个字符串)

这是一个类似的问题的答案,其中显示了如何为

Here's a similar question's answer which shows how to create a custom comparer for the Dictionary- constructor.

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

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