通常,如果我有这个:
public string Foo(string text)
{
return text.Substring(3);
}
Run Code Online (Sandbox Code Playgroud)
我会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);
}
Run Code Online (Sandbox Code Playgroud)
但现在我想使用另一种方法进行此验证:
public string Foo(string text)
{
Validator.WithArgument(text, "text").NotNullEmptyOrWhitespace().OfMinLength(3);
return text.Substring(3);
}
Run Code Online (Sandbox Code Playgroud)
因为该方法验证了参数,所以代码分析规则得到满足,但您仍然会收到CA1062警告.有没有办法抑制代码分析规则这样的情况,而不是每次都手动抑制它们或关闭特定的代码分析规则?
命名属性ValidatedNotNullAttribute可用于指示参数在辅助方法中经过验证。但是,对于流畅的验证 API 来说,它不一定是一个不错的选择,因为您需要将其添加到错误方法(您的WithArgument方法,而不是您的NotNullEmptyOrWhitespace方法)的参数中。
| 归档时间: |
|
| 查看次数: |
224 次 |
| 最近记录: |