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
How to test for an empty generic.dictionary collection?
提问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, reportGraphs
looks 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 empty
dictionary and null
. Calling MoveNext
on 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, reportGraphs
is null
if 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 foreach
statement:
执行此操作的另一种方法(避免显式枚举)是使用foreach
语句:
foreach (KeyValuePair<Key,Value> item in reportGraphs)
{
// do something
}
[Edit]Note that this example also presumes that reportGraphs
is never null
.
[编辑]请注意,此示例还假定reportGraphs
永远不会null
。