我有一个返回IEnumerable
对象的方法,但我发现有时(出错时)该方法返回IEnumerable
的空值。
该方法看起来像这样。
IEnumerable<string> function(String param1, String param2)
{
IEnumerable s = null;
s = (some query over here);
return s;
}
当我用param2
调用此方法时,函数内部失败并返回此时为null的s。
所以,要检测我使用过的,
IEnumerable<string> a = function(1,0);
if (a.count<string> > 0) //not working
if (a == 0) //not working.
在任何其他操作之前使用IEnumerable
并检查它是否为空的正确方法是什么?
答案 0 :(得分:3)
如果搜索结果为null,则可以返回空的枚举:
IEnumerable<string> function(String param1, String param2)
{
IEnumerable s = null;
s = (some query over here);
return s ?? Enumerable.Empty<string>();
}
答案 1 :(得分:1)
你的s = (some query over here);
返回null。这就是你得到例外的原因。
稍后您的检查应该是:
if(a != null)
和
if(a.Count() > 0)
您可以将两者合并为:
if(a!=null && a.Count() >0)
{
// do your work
}
答案 2 :(得分:1)
null
与没有任何元素的枚举不同。因此,您对if(a.count<string> > 0)
的检查失败。 (实际上,a
并未指向可以使用Count
检索其元素数量的任何实例。)
此外,null
与整数值0
不同。因此,您对if(a == 0)
的检查也会失败。
但是,null
是C#中的关键字,您可以与之比较:
if (a == null)