【问题标题】:Acsessing arrays in dictionary's访问字典中的数组
【发布时间】:2015-01-10 18:54:47
【问题描述】:

你好,我有这段代码

Dictionary<int[], char[]> items = new Dictionary<int[], char[]>();

我希望能够获得我尝试过的所有 int[] 和 char[] 的值

foreach (KeyValuePair<int[], char[]> kvp in items)
            {
                Console.WriteLine("Key = {0}, Value = {1}",
                    kvp.Key, kvp.Value);
            }

但这不起作用,它只是输出

Key = System32.Int32[], Value = System.Char[]
Key = System32.Int32[], Value = System.Char[]
Key = System32.Int32[], Value = System.Char[]
Key = System32.Int32[], Value = System.Char[]
Key = System32.Int32[], Value = System.Char[]

两个数组的长度相同,在本例中为 5,所以我只是想知道如何访问字典中的某些元素?正常的方法是行不通的。任何帮助是极大的赞赏。谢谢。

【问题讨论】:

  • 您有任何 int 数组作为键,您还期望输出什么? , 你知道在字典中有一个 int 数组作为键是没用的吗?
  • 您有一个 Int32[] 作为键和 Char[] 作为值。您读取的是这些值(在这种情况下是类型名称),而不是其中的值。
  • 是的,我明白没有密钥我无法访问 char 数组,但我想知道它是否可能?
  • 如何读取其中的值?有办法吗?
  • @Servy 我用谷歌搜索过了,证明我错了吗?

标签: c# arrays dictionary char int


【解决方案1】:

Console.WriteLine 在参数上调用ToString,您看到的是在不覆盖ToString 的类型上调用ToString 方法的行为。ToString 的默认实现返回类型名称。如果您想以其他格式显示您的值,则需要手动执行。

例如,如果您想以逗号分隔的格式显示数组值,您可以使用string.Join:

foreach (KeyValuePair<int[], char[]> kvp in items)
{
    Console.WriteLine("Key = {0}, Value = {1}",
                string.Join("," kvp.Key), string.Join("," kvp.Value));
}

【讨论】:

  • 谢谢你的作品。我怎样才能正常访问变量,例如 int j = items[1,1]?
  • @RaymondTunstill 你需要传递一个 int 数组作为键。但即使你传递了一个内容相同的数组,你也可能得不到你想要的值。因为默认情况下,数组是根据引用进行比较的。您需要为您的字典提供一个自定义相等比较器,以便它可以根据内容而不是引用来比较键。
  • 我该怎么做?
  • @RaymondTunstill 有一个示例 here 关于如何将 Dictionary 与自定义比较器一起使用,还有一个示例 here 关于如何实现自定义相等比较器
  • @RaymondTunstill 您可以创建一个类似class ArrayEqualsComparer&lt;T&gt; : EqualityComparer&lt;T[]&gt; where T : IComparable&lt;T&gt; { public override bool Equals(T[] x, T[] y) { return System.Collections.StructuralComparisons.StructuralEqualityComparer.Equals(x, y); } public override int GetHashCode(T[] obj) { return System.Collections.StructuralComparisons.StructuralEqualityComparer.GetHashCode(obj); } } 的类,然后将您的items 重新定义为items = new Dictionary&lt;int[], char[]&gt;(new ArrayEqualsComparer&lt;int&gt;());
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 2013-10-06
  • 1970-01-01
相关资源
最近更新 更多