您可以随时编写自己的字典。
解决方案 1:继承并使用“新”覆盖方法首先检查包含键。如果是,则通过键返回该值或通过 a
创建
Func<K, T>
代表。但是,通过界面使用此字典时,此解决方案将中断
IDictionary<K,T>
因此,您需要通过解决方案 2 更加彻底。
解决方案 2:使用内部字典的 Dictionary Wrapper - 其余与解决方案 1 相同。
解决方案 3:ConcurrentDictionary 提供 GetOrAdd,它也是线程安全的。
解决方案 4:类似于解决方案 2 的 ConcurrentDictionary Wrapper。
这是一个字典包装器:
public class WrappedDictionary<K, T> : IDictionary<K, T>
{
public IDictionary<K, T> WrappedInstance { get; set; }
public virtual T this[K key]
{
get
{
// CUSTOM RESOLUTION CODE GOES HERE
return this.WrappedInstance[key];
}
set
{
this.WrappedInstance[key] = value;
}
}
public int Count
{
get
{
return this.WrappedInstance.Count;
}
}
public bool IsReadOnly
{
get
{
return this.WrappedInstance.IsReadOnly;
}
}
public ICollection<K> Keys
{
get
{
return this.WrappedInstance.Keys;
}
}
public ICollection<T> Values
{
get
{
return this.WrappedInstance.Values;
}
}
public void Add(KeyValuePair<K, T> item)
{
this.WrappedInstance.Add(item);
}
public void Add(K key, T value)
{
this.WrappedInstance.Add(key, value);
}
public void Clear()
{
this.WrappedInstance.Clear();
}
public bool Contains(KeyValuePair<K, T> item)
{
return this.WrappedInstance.Contains(item);
}
public bool ContainsKey(K key)
{
return this.WrappedInstance.ContainsKey(key);
}
public void CopyTo(KeyValuePair<K, T>[] array, int arrayIndex)
{
this.WrappedInstance.CopyTo(array, arrayIndex);
}
public IEnumerator<KeyValuePair<K, T>> GetEnumerator()
{
return this.WrappedInstance.GetEnumerator();
}
public bool Remove(KeyValuePair<K, T> item)
{
return this.WrappedInstance.Remove(item);
}
public bool Remove(K key)
{
return this.WrappedInstance.Remove(key);
}
public bool TryGetValue(K key, out T value)
{
// CUSTOM RESOLUTION CODE GOES HERE
return this.WrappedInstance.TryGetValue(key, out value);
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.WrappedInstance.GetEnumerator();
}
}