【问题标题】:Dictionary key not working as a type of Tuple<int[], int>字典键不能作为 Tuple<int[], int> 的类型工作
【发布时间】:2014-03-28 19:40:14
【问题描述】:

我有一种情况,我需要一个带有这种类型键的字典,但之后似乎找不到等效键。

Dictionary<Tuple<int[], int>, object> cache = new Dictionary<Tuple<int[], int>, object>();

cache.Add(Tuple.Create(new int[]{1}, 1), new object());

Assert.That(cache.ContainsKey(Tuple.Create(new int[] { 1 }, 1))); // This fails

我已经使用Tuple&lt;int, int&gt; 对其进行了测试,它似乎工作正常,但就我而言,我确实需要某种Tuple&lt;int[], int&gt; 并且使用这种类型的密钥,它不起作用。

还有其他可行的替代方法吗?

【问题讨论】:

  • 那么你的错误是什么?
  • 问题是我无法使用那种类型的元组在我的 dicco 中查找
  • 那是因为你不能像here那样比较数组

标签: c# dictionary


【解决方案1】:

数组是不可比较的。例如:

var array1 = new int[] { 1 };
var array2 = new int[] { 1 };
Debug.WriteLine(array1 == array2); // this returns false
Debug.WriteLine(Object.Equals(array1, array2)) // this returns false

您需要做以下两件事之一:

1) 将 int[] 替换为实现必要的 EqualsGetHashCode 覆盖的自定义类。

2) 编写一个实现IEqualityComparer&lt;Tuple&lt;int[], int&gt;&gt; 的类。该类将为Tuple&lt;int[], int&gt;s 提供EqualsGetHashCode 方法。将该类的实例提供给您的Dictionary&lt;Tuple&lt;int[], int&gt;, object&gt;

【讨论】:

    【解决方案2】:

    你不能和==比较数组你can use this code

     static bool ArraysEqual<T>(T[] array1, T[] array2)
        {
            if (ReferenceEquals(array1,array2))
                return true;
    
            if (array1 == null || array2 == null)
                return false;
    
            if (array1.Length != array2.Length)
                return false;
    
            EqualityComparer<T> comparer = EqualityComparer<T>.Default;
            for (int i = 0; i < array1.Length; i++)
            {
                if (!comparer.Equals(array1[i], array2[i])) return false;
            }
            return true;
        }
    

    【讨论】:

      猜你喜欢
      • 2014-09-18
      • 2015-01-17
      • 2021-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多