gpt4 book ai didi

c# - Parasoft 无法识别自定义 IEnumerable 扩展方法 .IsNullOrEmpty()

转载 作者:行者123 更新时间:2023-11-30 12:38:08 25 4
gpt4 key购买 nike

我们有一个自定义的扩展方法 .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 不认为这是一个有效的 null 检查,它给出了一个

BD.EXCEPT.NR-1: Avoid 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 识别我们的扩展方法?

最佳答案

如果目标为 null,则不能对其调用方法,它会崩溃。

您仍然需要空检查。

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

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

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

关于c# - Parasoft 无法识别自定义 IEnumerable 扩展方法 .IsNullOrEmpty(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55580606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com