首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Parasoft不识别自定义IEnumerable扩展方法.IsNullOrEmpty()

Parasoft不识别自定义IEnumerable扩展方法.IsNullOrEmpty()
EN

Stack Overflow用户
提问于 2019-04-08 19:36:41
回答 1查看 97关注 0票数 4

我们有一个定制的扩展方法.IsNullOrEmpty(),它完全按照它听起来的那样做。

代码语言:javascript
复制
public static bool IsNullOrEmpty<T>(this IEnumerable<T> target)
{
  bool flag = true;
  if (target != null)
  {
    using (IEnumerator<T> enumerator = target.GetEnumerator())
    {
      if (enumerator.MoveNext())
      {
        T current = enumerator.Current;
        flag = false;
      }
    }
  }
  return flag;
}

但是,parasoft不承认这是一个有效的空检查,它提供了一个

BD.EXCEPT.NR-1:避免NullReferenceException

在使用扩展方法后不久。

示例:

代码语言:javascript
复制
IEnumerable<Foo> foos = _repo.GetFoos();
IEnumerable<Bar> bars;

if (!foos.IsNullOrEmpty())
{
    bars = foos.Select(foo => foo.Bar);  // This is where the Parasoft violation would occur.
}

是否有办法使Parasoft识别我们的扩展方法?

EN

回答 1

Stack Overflow用户

发布于 2019-04-08 19:43:24

如果目标为null,则不能在其上调用方法,它会爆炸。

您仍然需要空检查。

代码语言:javascript
复制
if (foos != null && !foos.IsNullOrEmpty())
{
    bars = foos.Select(foo => foo.Bar);  // This is where the Parasoft violation would occur.
}

另一种方法是创建一个函数来检查它是否有数据(与您的函数相反),然后您可以调用?在这种情况下,空对象和布尔值上的运算符将返回FALSE,这是可取的。

代码语言:javascript
复制
if (foos?.Any())
{
    bars = foos.Select(foo => foo.Bar);  // This is where the Parasoft violation would occur.
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55580606

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档