加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 代码分析规则CA1062行为

发布时间:2020-12-15 08:20:28 所属栏目:百科 来源:网络整理
导读:我有以下字符串扩展方法: public static bool IsNullOrEmpty(this string target){ return string.IsNullOrEmpty(target);} …在代码中我使用如下: public static string DoSomethingOnString(this string target){ if (target.IsNullOrEmpty()) return ta
我有以下字符串扩展方法:
public static bool IsNullOrEmpty(this string target)
{
    return string.IsNullOrEmpty(target);
}

…在代码中我使用如下:

public static string DoSomethingOnString(this string target)
{
    if (target.IsNullOrEmpty())
        return target;

    target = target.Trim();  //This line causes CA1062 violation

    return target;
}

现在,如果我对此进行代码分析,则会违反规则CA1062.
但是,如果我将代码更改为:

public static string DoSomethingOnString(this string target)
{
    if (string.IsNullOrEmpty(target))  //CHANGED LINE
        return target;

    target = target.Trim();  //This line DOES NOT cause CA1062 violation anymore

    return target;
}

……那很好.

为什么它认为我在第一个例子中没有检查空状态?它只检查string.IsNullOrEmpty或string.IsNullOrWhiteSpace吗?有没有办法让CA识别我的扩展方法,或者我需要压制这个规则?

更新:
如果您遇到同样的问题,可以对我在MS Connect上提交的反馈项进行投票:
Code Analysis rule CA1062 raises false alarm

解决方法

Why it thinks that I’m not checking for null condition in the first example?

很简单,如果你的IsNullOrEmpty扩展方法与string.IsNullOrEmpty做同样的事情,FxCop不明白.它没有意识到如果target为null,则IsNullOrEmpty将返回true并且您的方法将退出.基本上我怀疑它有内置的string.IsNullOrEmpty知识. Code Contracts更有可能在这里获得成功,因为我相信与代码契约的深层推理相比,FxCop只对代码执行的操作执行相对较浅的检查.您可以使用ValidatedNotNullAttribute修饰IsNullOrEmpty方法,以通知FxCop发生了什么.

public static bool IsNullOrEmpty([ValidatedNotNullAttribute] this string target)
{
    return string.IsNullOrEmpty(target);
}
//The naming is important to inform FxCop
sealed class ValidatedNotNullAttribute : Attribute { }

这只是代码分析有时候太急于批评的一个例子.这是我用过的几乎所有代码分析工具都能看到的东西.您的选择通常是:

>更改代码以解决代码分析工具,即使之前没问题
>手动检查每个规则后,取消特定站点的规则
>如果他们经常给出误报,则取消整个规则
>完全放弃代码分析工具

您还应该记录错误或功能请求,当然……

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读