c# - 如何让代码分析发现一个参数在被调用的方法中得到验证

标签 c# code-analysis

通常如果我有这个:

public string Foo(string text)
{
    return text.Substring(3);
}

我会从代码分析中得到一个CA1062: Validate arguments of public methods。它可以通过修改代码来修复:

public string Foo(string text)
{
    if (text == null)
        throw new ArgumentNullException("text");
    else if (string.IsNullEmptyOrWhiteSpace(text)
        throw new ArgumentException("May not be empty or white space", "text")
    else if (text.Length < 3)
        throw new ArgumentException("Must be at least 3 characters long", "text");
    return text.Substring(3);
}

但现在我想使用另一种方法来进行此验证:

public string Foo(string text)
{
    Validator.WithArgument(text, "text").NotNullEmptyOrWhitespace().OfMinLength(3);
    return text.Substring(3);
}

由于该方法验证了参数,因此满足代码分析规则,但您仍然会收到 CA1062 警告。有没有一种方法可以抑制此类情况的代码分析规则,而无需每次都手动抑制它们或关闭特定的代码分析规则?

最佳答案

名为 ValidatedNotNullAttribute 的属性可用于指示在辅助方法中验证参数。但是,自 you would need to add it to a parameter of the wrong method 以来,它不一定是流畅验证 API 的最佳选择。 (您的 WithArgument 方法,与您的 NotNullEmptyOrWhitespace 方法相对)。

关于c# - 如何让代码分析发现一个参数在被调用的方法中得到验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15051098/

相关文章:

c# - 如何创建动态属性

c# - Entity Framework 代码优先 - 将 smallint 和整数转换为 int32

c# - 使用 Linq 和 Lambda 表达式从表中选择多个字段

c# - 如何修复 CA2100 Review SQL 查询的安全漏洞问题

visual-studio-2010 - 代码分析作为本地警告但在 TFS 构建时出错

c# - 将 Dapper MultiMapper 与外连接查询结合使用

c# - "Data source name not found and no default driver specified"错误

c - 这里缺少哪些头文件(C 代码)?

.net - VB.NET 中的公共(public)变量和公共(public)属性有什么区别? (代码分析VS2010,CA1051 : Microsoft.设计)

java - 使用 SonarQube 5.4 配置 CheckStyle