IEnumerable中的异常,当它为null时

时间:2012-08-29 10:11:49

标签: c# .net visual-studio-2010

我有一个返回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并检查它是否为空的正确方法是什么?

3 个答案:

答案 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)