为什么C#TryAdd,TryRemove,TryGetValue在失败时返回空集?

时间:2016-02-15 13:34:48

标签: c# exception dictionary nullreferenceexception hashset

为什么Dictionary方法在失败时返回空集?

  

如果答案是“您希望他们返回什么?”我想我是   期待一个空的HashSet,我可以运行像Count或   GetEnumerator上。没有例外。

     

也许我的问题确实是,如果我捕获异常,使返回值不为null然后返回它?

我看了this question,但是当我调用Add(),Remove()或TryGetValue()

时,我的字典不为空

是的,这是一个编程分配,但数据结构是我的选择,用两个ConcurrentDictionaries表示图形。

测试运行时:

DependencyGraph t = new DependencyGraph();
Assert.IsFalse(t.GetDependees("x").GetEnumerator().MoveNext());

我的方法运行:

    public IEnumerable<string> GetDependees(string s)
    {
        HashSet<String> valuesForKey = new HashSet<String>();
        dependeeGraph.TryGetValue(s, out valuesForKey);
        return valuesForKey;
    }

当它返回值.GetEnumerator().MoveNext()时,我得到nullReferenceException。

2 个答案:

答案 0 :(得分:3)

哦,男孩......

停止忽略返回值。返回值告诉您&#34;没有可用的数据&#34;。设置out参数的唯一原因是因为C#要求您这样做 - 您不应该使用该值。

如果你不关心&#34;没有数据&#34;和#34;一个零项目的集合&#34;,您可以编写自己的扩展方法来简化事情:

public static IEnumerable<string> GetValueOrEmpty(this DependencyGraph dg, string s)
{
  HashSet<string> value;

  if (!dg.TryGetValue(s, out value)) return Enumerable.Empty<string>();

  return value;
}

答案 1 :(得分:2)

TryGetValue out类型参数的TValue参数。由于out参数必须由被调用函数初始化,因此TryGetValue必须为每种可能的类型执行此操作。唯一的这样的值是default(TValue),对于引用类型是null,对于值类型是'零'。