通常如果我有这个:
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/