gpt4 book ai didi

用于查找的 C# 最佳 IDictionary 用法,可能找不到

转载 作者:太空狗 更新时间:2023-10-29 18:11:06 24 4
gpt4 key购买 nike

假设我有如下方法:

internal MyClass GetValue(long key)
{
if (_myDictionary.ContainsKey(key))
return _myDictionary[key];

return null; // Not found
}

IDictionary<long,MyClass> _myDictionary=...

但是上面的代码在字典中有两次查找:

  1. 测试 key 是否存在
  2. 实际检索值

是否有更优化的方式来表述这样的函数,以便只执行一次查找,但“未找到”的情况仍通过空返回处理(即,不通过未找到异常)?

例如,如果对键的查找返回某种可用于检索值的迭代器,或者如果未找到该值(如在 C++ 中所做的那样)则返回无效的迭代器,那就太好了。考虑到 C# 的语言特性,也许 C# 有更好的方法来做到这一点。

最佳答案

TryGetValue方法正是为这种情况而设计的——避免两次查找操作。

This method combines the functionality of the ContainsKey method and the Item property.

If the key is not found, then the value parameter gets the appropriate default value for the value type TValue.

[...] Use the TryGetValue method if your code frequently attempts to access keys that are not in the dictionary. Using this method is more efficient than catching the KeyNotFoundException thrown by the Item property.

internal MyClass GetValue(long key)
{
MyClass maybeValue;

// Normally, one would inspect the return value of this method
// but in this case, it's not necessary since a failed lookup
// will set the out argument to default(valType), which is null
// for a reference type - exactly what you want.
_myDictionary.TryGetValue(key, out maybeValue);

return maybeValue;
}

关于用于查找的 C# 最佳 IDictionary 用法,可能找不到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9485225/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com