结合使用代码分析和代码合同时,我收到很多警告,例如
CA1062:Microsoft.Design:在外部可见的方法“Foo.Bar(Log)”中,在使用之前验证参数“log”。
在 Foo.Bar 中,我有一个验证log
.
public Bar(Log log)
{
Contract.Requires(log != null);
log.Lines.Add(...);
// ...
}
有没有办法让 FxCop 理解代码合约?
结合使用代码分析和代码合同时,我收到很多警告,例如
CA1062:Microsoft.Design:在外部可见的方法“Foo.Bar(Log)”中,在使用之前验证参数“log”。
在 Foo.Bar 中,我有一个验证log
.
public Bar(Log log)
{
Contract.Requires(log != null);
log.Lines.Add(...);
// ...
}
有没有办法让 FxCop 理解代码合约?
不,我认为在当前版本中不可能,因为由合约重写器生成的代码不会产生 FxCop 正在寻找的标准模式。
通常,虽然我在使用代码合同时禁用了这个特定的 FxCop 规则。我发现静态验证器足以弥补这条规则的缺失,因为它会比 FxCop 更积极地大喊缺乏检查。我会在这里建议相同的方法,它会为你解决这个问题。
是的,正如我在此处的回答中所述,从框架的 4.5.2 版本(可能是 4.5)开始,可以通知代码分析正在执行的代码合同。扩展方法和标记属性类必须像这样定义:
public static class ContractExtensions {
/// <summary>Throws <c>ContractException{name}</c> if <c>value</c> is null.</summary>
/// <param name="value">Value to be tested.</param>
/// <param name="name">Name of the parameter being tested, for use in the exception thrown.</param>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "name")]
[ContractAbbreviator] // Requires Assemble Mode = Standard Contract Requires
public static void ContractedNotNull<T>([ValidatedNotNull]this T value, string name) where T : class {
Contract.Requires(value != null,name);
}
}
/// <summary>Decorator for an incoming parameter that is contractually enforced as NotNull.</summary>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class ValidatedNotNullAttribute : global::System.Attribute {}
其他详细信息在我的其他答案中。
像这样指定 ArgumentNullException 异常:
public Bar(Log log)
{
Contract.Requires<ArgumentNullException>(log != null);
log.Lines.Add(...);
// ...
}
Fxcop 期望抛出 ArgumentNullException 异常...