111,098
社区成员




private int FindEntry(TKey key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (this.buckets != null)
{
int num = this.comparer.GetHashCode(key) & int.MaxValue;
for (int i = this.buckets[num % this.buckets.Length]; i >= 0; i = this.entries[i].next)
{
if (this.entries[i].hashCode == num && this.comparer.Equals(this.entries[i].key, key))
{
return i;
}
}
}
return -1;
}
static void Main(string[] args)
{
//测试数据
Dictionary<int[], string> d = new Dictionary<int[], string>(new ArrEqualityComparer());
int[] a = {1, 1, 1};
d.Add(a, “1”);
a[0] = 0;
d.Add(a, “2”);
}
以上代码测试可行,但是单步调试发现字典d中的两个Key中的值均为{0, 1, 1},并且d[new[] {0, 1, 1}]得到的值为2
请问该方法是不是还有地方需要完善?
@正怒月神[/quote]
没相处太好的办法。
不过我觉得你为何不存储一个 string.Join(",",a); 的字符串。类似 "1,2,3"当做key呢?
[/quote]
@正怒月神 谢谢 用字符串代替int[]是个好办法,后来我也是这样实现的
static void Main(string[] args)
{
//测试数据
Dictionary<int[], string> d = new Dictionary<int[], string>(new ArrEqualityComparer());
int[] a = {1, 1, 1};
d.Add(a, “1”);
a[0] = 0;
d.Add(a, “2”);
}
以上代码测试可行,但是单步调试发现字典d中的两个Key中的值均为{0, 1, 1},并且d[new[] {0, 1, 1}]得到的值为2
请问该方法是不是还有地方需要完善?
@正怒月神[/quote]
没相处太好的办法。
不过我觉得你为何不存储一个 string.Join(",",a); 的字符串。类似 "1,2,3"当做key呢?
static void Main(string[] args)
{
//测试数据
Dictionary<int[], string> d = new Dictionary<int[], string>(new ArrEqualityComparer());
int[] a = {1, 1, 1};
d.Add(a, “1”);
a[0] = 0;
d.Add(a, “2”);
}
以上代码测试可行,但是单步调试发现字典d中的两个Key中的值均为{0, 1, 1},并且d[new[] {0, 1, 1}]得到的值为2
请问该方法是不是还有地方需要完善?
@正怒月神static void Main(string[] args)
{
//测试数据
Dictionary<int[], string> d = new Dictionary<int[], string>(new ArrEqualityComparer());
int[] a = { 1, 2, 3 };
string b = "hello";
d.Add(a, b);
//使用新实例的 key查找
int[] a1 = { 1, 2, 3 };
Console.WriteLine(d[a1]);
Console.ReadLine();
}
//重写key的判断方法
public class ArrEqualityComparer : IEqualityComparer<int[]>
{
public bool Equals(int[] b1, int[] b2)
{
bool result = true;
for (int i = 0; i < b1.Length; i++)
{
if (b1[i] != b2[i])
{
result = false;
break;
}
}
return result;
}
public int GetHashCode(int[] arr)
{
int hCode = arr.Sum();
return hCode.GetHashCode();
}
}
//
// 摘要:
// 初始化 System.Collections.Generic.Dictionary<TKey,TValue> 类的新实例,该实例为空且具有默认的初始容量,并使用指定的
// System.Collections.Generic.IEqualityComparer<T>。
//
// 参数:
// comparer:
// 比较键时要使用的 System.Collections.Generic.IEqualityComparer<T> 实现,或者为 null,以便为键类型使用默认的
// System.Collections.Generic.EqualityComparer<T>。
public Dictionary(IEqualityComparer<TKey> comparer);