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

发布于 2024-08-18 03:22:00 字数 385 浏览 7 评论 0原文

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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

遇到 2024-08-25 03:22:00

如果它是通用词典,您可以检查 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 an IEnumerator<T> - is there a reason your enumerating your collection by hand?

罪#恶を代价 2024-08-25 03:22:00

empty 字典和 null 之间是有区别的。对空集合调用 MoveNext 不会导致 NullReferenceException。我想在你的情况下你可以测试reportGraphs != null

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文