Mar*_*rek 14 .net c# exception idictionary
文档声明bool Dictionary<TKey, TValue>.ContainsKey(TKey key)在传递null键时抛出异常.谁能说出理由呢?如果它刚刚归来,它会不会更实际false?
这就是它的实现方式:( 来源)
public bool ContainsKey(TKey key) {
return FindEntry(key) >= 0;
}
Run Code Online (Sandbox Code Playgroud)
方法FindEntry如下:
private int FindEntry(TKey key) {
if( key == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets != null) {
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next) {
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) return i;
}
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)
由于null不允许在字典中使用值作为键.
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add(null, 10);
Run Code Online (Sandbox Code Playgroud)
以上将产生一个例外:
值不能为空.参数名称:key
对于你的问题:
如果它只是返回假是不是更实际?
微软的某个人可能会回答这个问题.但IMO,因为null不允许为密钥添加值,所以检查null密钥是没有意义的ContainsKey
| 归档时间: |
|
| 查看次数: |
9134 次 |
| 最近记录: |