C# 如何测试空的 generic.dictionary 集合?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2088937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:24:57  来源:igfitidea点击:

How to test for an empty generic.dictionary collection?

c#collectionsgenericsnullreferenceexception

提问by DEH

How do I test a generic dictionary object to see whether it is empty? I want to run some code as follows:

如何测试通用字典对象以查看它是否为空?我想按如下方式运行一些代码:

while (reportGraphs.MoveNext())
{
    reportGraph = (ReportGraph)reportGraphs.Current.Value;
    report.ContainsGraphs = true;
    break;
}

The reportGraph object is of type System.Collections.Generic.Dictionary When running this code then the reportGraphs dictionary is empty and MoveNext() immediately throws a NullReferenceException. I don't want to put a try-catch around the block if there is a more performant way of handling the empty collection.

reportGraph 对象的类型为 System.Collections.Generic.Dictionary 运行此代码时,reportGraphs 字典为空,并且 MoveNext() 立即抛出 NullReferenceException。如果有更高效的处理空集合的方法,我不想在块周围放置 try-catch。

Thanks.

谢谢。

采纳答案by Reed Copsey

If it's a generic dictionary, you can just check Dictionary.Count. Count will be 0 if it's empty.

如果它是一个通用字典,你可以只检查Dictionary.Count。如果为空,计数将为 0。

However, in your case, reportGraphslooks like it's an IEnumerator<T>- is there a reason your enumerating your collection by hand?

但是,在您的情况下,reportGraphs看起来像是IEnumerator<T>- 您是否有理由手动枚举您的收藏?

回答by Darin Dimitrov

There's a difference between an emptydictionary and null. Calling MoveNexton an empty collection won't result in a NullReferenceException. I guess in your case you could test if reportGraphs != null.

这里有一个之间的差异empty词典null。调用MoveNext空集合不会导致NullReferenceException. 我想在您的情况下,您可以测试是否reportGraphs != null.

回答by Groo

As Darin said, reportGraphsis nullif it throws a NullReferenceException. The best way would be to ensure that it is never null (i.e. make sure that it is initialized in your class' constructor).

正如达林说,reportGraphs就是null如果它抛出一个NullReferenceException。最好的方法是确保它永远不会为空(即确保它在类的构造函数中初始化)。

Another way to do this (to avoid enumerating explicitly) would be to use a foreachstatement:

执行此操作的另一种方法(避免显式枚举)是使用foreach语句:

foreach (KeyValuePair<Key,Value> item in reportGraphs)
{
    // do something
}

[Edit]Note that this example also presumes that reportGraphsis never null.

[编辑]请注意,此示例还假定reportGraphs永远不会null