c# - Parasoft 无法识别自定义 IEnumerable 扩展方法 .IsNullOrEmpty()
问题描述
我们有一个自定义扩展方法.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 识别我们的扩展方法?
解决方案
如果目标是空的,你不能调用它的方法,它会爆炸。
你仍然需要空检查。
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.
}
推荐阅读
- json - 需要使用 Spring Boot 从 OpenWeather json 获取温度
- node.js - 如何查看 Koa 的 ctx.query 的内容?
- ios - 当应用程序处于后台或关闭时,React Native Firebase 推送通知不起作用
- typo3 - TYPO3 FAL fe_user 没有标识符?
- python - YouTube Data Api:如果达到配额限制,则打破 nextPageToken while 循环?
- python - os 模块 python 正在工作,但输出不正确
- regex - 如何为文本字段实现正则表达式以在 Extjs 中一次允许一个逗号一个点
- laravel - Laravel - 试图获取非对象的属性“名称”
- java - Spring SAML:后退浏览器按钮导致验证 SAML 消息时出错
- ios - React Native 0.60.4 从 0.59.9 升级