Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Parasoft无法识别自定义IEnumerable扩展方法。IsNullOrEmpty()_C#_Parasoft - Fatal编程技术网

C# Parasoft无法识别自定义IEnumerable扩展方法。IsNullOrEmpty()

C# Parasoft无法识别自定义IEnumerable扩展方法。IsNullOrEmpty(),c#,parasoft,C#,Parasoft,我们有一个自定义扩展方法.IsNullOrEmpty(),它的功能与听起来的完全相同 public static bool IsNullOrEmpty<T>(this IEnumerable<T> target) { bool flag = true; if (target != null) { using (IEnumerator<T> enumerator = target.GetEnumerator()) { if

我们有一个自定义扩展方法
.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;
}
publicstaticbool为空(此IEnumerable目标)
{
布尔标志=真;
如果(目标!=null)
{
使用(IEnumerator enumerator=target.GetEnumerator())
{
if(枚举数.MoveNext())
{
T current=枚举数。current;
flag=false;
}
}
}
返回标志;
}
然而,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.
}
IEnumerable foos=_repo.GetFoos();
可数条;
如果(!foos.IsNullOrEmpty())
{
Bar=foos.Select(foo=>foo.Bar);//这就是Parasoft违规的地方。
}

有没有办法让Parasoft识别我们的扩展方法?

如果目标为空,您不能对其调用方法,它会爆炸

您仍然需要空检查

if (foos != null && !foos.IsNullOrEmpty())
{
    bars = foos.Select(foo => foo.Bar);  // This is where the Parasoft violation would occur.
}
另一种方法是创建一个函数来检查它是否有数据(与函数相反),然后可以调用?在这种情况下,空对象上的运算符和布尔值将返回FALSE,这是需要的

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

您的
IsNullOrEmpty
不会检查序列中的所有项是否都不为空。因此,如果
foos
中至少有一项为空,那么在执行
foo.Bar
时,您将获得NRE。您可以在foo和Bar上添加类信息吗?您的扩展方法在检查自定义类IEnumerable是否有空数据方面不是最好的方法,但我们需要更多信息以获得最佳帮助。如果(!foos.IsNullOrEmpty()&&!(foos is null)),您是否仍然看到带有
的消息?顺便说一句,为什么不仅仅是
返回!(目标?.Any()==true)?都是遗留代码。我被要求检查并解决一些parasoft违规行为。这种扩展方法在整个代码库中使用了100多次。我不能给你一个他们选择使用它的好理由。@JED
var x=new Foo[1]{null}
是一个非null、非空枚举的示例,它将抛出NRE for
x.First().Bar
(因为序列的一个元素为null)。有两个潜在的NRE——所以即使解决第一个(这似乎是这个问题的核心)也不会消除第二个。您可能希望使用
foos.Select(foo=>foo?.Bar)发布帖子
为了澄清您只关心确认为非空/非空的
foos
。我认为OP知道空引用异常,但希望静态分析工具检测其
块的主体,如果
块是安全的,您可以调用
null
上的扩展方法。“如果目标为null,则无法对其调用方法,它将爆炸。”-这与扩展问题有何关系?如果我执行
If(foos?.Any()){}
我会得到一个错误,即可为null的bool不能隐式转换为bool。它必须是
If(foos?.Any()==true)){}
即使我将扩展方法更改为等于
if(foos?.Any()==true)
,parasoft冲突仍然会发生。