如何测试空的 generic.dictionary 集合?
如何测试通用字典对象以查看它是否为空?我想运行一些代码,如下所示:
while (reportGraphs.MoveNext())
{
reportGraph = (ReportGraph)reportGraphs.Current.Value;
report.ContainsGraphs = true;
break;
}
reportGraph 对象的类型为 System.Collections.Generic.Dictionary 运行此代码时,reportGraphs 字典为空,MoveNext() 立即抛出 NullReferenceException。如果有更高效的方法来处理空集合,我不想在块周围放置 try-catch。
谢谢。
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.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果它是通用词典,您可以检查 Dictionary.Count< /a>.如果为空,则计数为 0。
但是,就您而言,
reportGraphs
看起来像是一个IEnumerator
- 您手动枚举集合是否有原因?If it's a generic dictionary, you can just check Dictionary.Count. Count will be 0 if it's empty.
However, in your case,
reportGraphs
looks like it's anIEnumerator<T>
- is there a reason your enumerating your collection by hand?empty
字典和null
之间是有区别的。对空集合调用MoveNext
不会导致NullReferenceException
。我想在你的情况下你可以测试reportGraphs != null
。There's a difference between an
empty
dictionary andnull
. CallingMoveNext
on an empty collection won't result in aNullReferenceException
. I guess in your case you could test ifreportGraphs != null
.