c# - 使用自定义参数验证助手中断代码分析

标签 c# validation code-analysis static-code-analysis

我想使用自定义助手来简化参数验证,就像这样。

public static void ThrowIfNull(this object value, string parameterName)
{
    if (value == null)
    {
        throw new ArgumentNullException(parameterName);
    }
}

但是,静态代码分析当然不知道我在使用此帮助程序时确实验证了公共(public)方法中的输入,因此它给我 CA1062 关于公共(public)方法参数未被验证的错误。

具体问题是 this one .

有没有办法教导代码分析器这个助手处理参数空值验证?这个问题的正确解决方案是什么?

最佳答案

使用以下名称创建属性:

[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
public sealed class ValidatedNotNullAttribute : Attribute {}

然后将其应用于您正在验证的参数:

public static void ThrowIfNull([ValidatedNotNull] this object value, string parameterName)
{
    if (value == null)
    {
        throw new ArgumentNullException(parameterName);
    }
}

并且警告应该消失。

你可以看到这个属性被很多库使用,包括 .net 框架本身,例如 here .

关于c# - 使用自定义参数验证助手中断代码分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44005383/

相关文章:

c# - 异步/等待与线程场景

c# - 在 Autofac : What is the difference between a Service and a Component? 的上下文中

vb.net - 当用户关闭应用程序时禁用对所有表单的验证

c# - CA1001 在异步方法上实现 IDisposable

c# - Visual Studio Designer - 限制属性网格以显示语言属性的某些特定语言

c# - 如何正确编写异步方法?

asp.net-mvc - 什么是 ASP.NET MVC 的验证选项

asp.net-mvc - asp.net mvc - 整数字段的 optional/默认值

c - 生成数据通信流图(C程序,profiling)

c# - CA1819 : Properties should not return arrays. 此规则是否也适用于其他对象?