-1

我有一个返回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在任何其他操作之前使用并检查它是否为空的正确方法是什么?

4

3 回答 3

3

如果搜索结果为空,您可以返回一个空的可枚举:

IEnumerable<string> function(String param1, String param2)
  {
         IEnumerable s = null;

         s = (some query over here);

         return s ?? Enumerable.Empty<string>();
  }
于 2012-08-29T10:18:25.327 回答
1

s = (some query over here);的返回null。这就是为什么你得到例外。

稍后您的支票应该是:

if(a != null)

if(a.Count() > 0)

您可以将两者结合为:

if(a!=null && a.Count() >0)
{
 // do your work
}
于 2012-08-29T10:13:00.380 回答
1

null与没有任何元素的枚举不同。因此,您的检查if(a.count<string> > 0)失败。(实际上,a它没有指向任何可以使用 检索其元素数量的实例Count。)

此外,null与整数值不同0。因此,您的检查if(a == 0)也失败了。

但是,null是 C# 中的关键字,您可以与之进行比较:

if (a == null)
于 2012-08-29T10:18:15.900 回答