当组合使用代码分析和代码合同时,我会收到很多警告,例如
CA1062:Microsoft.Design:在外部可见方法'Foo.Bar(Log)'中,在使用之前验证参数'log'。
在Foo.Bar中,我有一份合同,用于验证log
。
public Bar(Log log)
{
Contract.Requires(log != null);
log.Lines.Add(...);
// ...
}
有没有办法让FxCop理解代码合约?
答案 0 :(得分:14)
不,我认为在当前构建中不可能,因为合同重写器生成的代码不会产生FxCop正在寻找的标准模式。
通常我在使用代码契约时禁用此特定FxCop规则。我发现静态验证器不仅可以弥补这条规则的损失,因为它会比FxCop更加积极地对缺乏检查感到愤怒。我会建议在这里采用相同的方法来解决这个问题。
答案 1 :(得分:3)
是,as noted in my answer here,从框架版本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 {}
其他详细信息在我的另一个答案中。
答案 2 :(得分:-2)
指定ArgumentNullException异常,如下所示:
public Bar(Log log)
{
Contract.Requires<ArgumentNullException>(log != null);
log.Lines.Add(...);
// ...
}
Fxcop希望抛出ArgumentNullException异常......