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

DEH*_*DEH 12 c# generics collections nullreferenceexception

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

while (reportGraphs.MoveNext())
{
    reportGraph = (ReportGraph)reportGraphs.Current.Value;
    report.ContainsGraphs = true;
    break;
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

Ree*_*sey 20

如果它是通用字典,您只需检查Dictionary.Count即可.如果它为空,则计数为0.

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


Dar*_*rov 6

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