4

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

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

使用扩展方法后不久。

例子:

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 识别我们的扩展方法?

4

1 回答 1

1

如果目标是空的,你不能调用它的方法,它会爆炸。

你仍然需要空检查。

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

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

if (foos?.Any())
{
    bars = foos.Select(foo => foo.Bar);  // This is where the Parasoft violation would occur.
}
于 2019-04-08T19:43:24.060 回答