正在声明内部字典比较器C#
本文关键字:比较器 字典 内部 声明 | 更新日期: 2023-09-27 18:21:48
我有一个字典,如下
Dictionary<ulong, Dictionary<byte[], byte[]>> Info;
内部字典保存一个byte[]数组作为关键字。
我无法理解如何为Info
字典声明构造函数。对于内部密钥比较,我有ByteArrayComparer
、
public class ByteArrayComparer : IEqualityComparer<byte[]>
{
public bool Equals(byte[] left, byte[] right)
{
if (left == null || right == null)
{
return left == right;
}
if (left.Length != right.Length)
{
return false;
}
for (int i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
public int GetHashCode(byte[] key)
{
if (key == null)
throw new ArgumentNullException("key");
int sum = 0;
foreach (byte cur in key)
{
sum += cur;
}
return sum;
}
}
我从SO Here 那里买的
请告知
比较器的规范不会直接作为Info
初始化的一部分,而是当您创建一个值以将放入外部字典时。例如:
// It's stateless, so let's just use one of them.
private static readonly IEqualityComparer<byte[]> ByteArrayComparerInstance
= new ByteArrayComparer();
Dictionary<ulong, Dictionary<byte[], byte[]>> Info
= new Dictionary<ulong, Dictionary<byte[], byte[]>();
....
...
Dictionary<byte[], byte[]> valueMap;
if (!Info.TryGetValue(key, out valueMap))
{
valueMap = new Dictionary<byte[], byte[]>(ByteArrayComparerInstance);
Info[key] = valueMap;
}
...
创建时,Info
内部没有任何字典,因此在该步骤中无法真正定义comparere。您必须为添加到Info
对象中的每个项目执行此操作。