不幸Dictionary
的是,框架提供的不提供此功能。最快的解决方法是构建这样的东西
public class UniqueValueDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
public new void Add(TKey key, TValue value)
{
if (this.ContainsValue(value))
{
throw new ArgumentException("value already exist");
}
base.Add(key, value);
}
public new TValue this[TKey key]
{
get
{
return base[key];
}
set
{
if (this.ContainsValue(value))
{
throw new ArgumentException("value already exist");
}
base[key] = value;
}
}
}
或类似以下的东西(性能更好,但内存不行)
public class UniqueValueDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
Dictionary<TValue, TKey> valueAsKey = new Dictionary<TValue, TKey>();
public new void Add(TKey key, TValue value)
{
if (valueAsKey.ContainsKey(value))
{
throw new ArgumentException("value already exist");
}
base.Add(key, value);
valueAsKey.Add(value, key);
}
public new TValue this[TKey key]
{
get
{
return base[key];
}
set
{
if (valueAsKey.ContainsKey(value))
{
throw new ArgumentException("value already exist");
}
if (!this.ContainsKey(key))
{
this.Add(key, value);
}
else
{
base[key] = value;
valueAsKey[value] = key;
}
}
}
//You may need to handle remove as well
}
注意:这仅在您使用UniqueValueDictionary<TKey, TValue>
类型时才有效,如果您强制转换Dictionary<TKey, TValue>
,则可以添加重复值。
正如评论中所指出的,您可以构建类似这样的东西,IDictionary<TKey, TValue>
而不是Dictionary<TKey, TValue>
将其作为一个想法。