可以让代码分析理解代码合同吗?

在组合使用代码分析和代码合同时,我会收到很多警告

CA1062 :Microsoft.Design:在外部可见方法’Foo.Bar(Log)’中,在使用之前validation参数’log’。

在Foo.Bar中,我有一个validationlog的合同。

 public Bar(Log log) { Contract.Requires(log != null); log.Lines.Add(...); // ... } 

有没有办法让FxCop理解代码合同?

不,我认为在当前构建中不可能,因为合同重写器生成的代码不会产生FxCop正在寻找的标准模式。

通常虽然我在使用代码契约时禁用了这个特定的FxCop规则。 我发现静态validation器不仅可以弥补这条规则的损失,因为它会比FxCop更加积极地进行检查。 我建议采用相同的方法来解决这个问题。

是的, 正如我在这里的回答所述 ,从框架的4.5.2版本(可能是4.5)开始,可以通知代码分析正在执行的代码合同。 必须像这样定义扩展方法和标记属性类:

  public static class ContractExtensions { /// Throws ContractException{name} if value is null. /// Value to be tested. /// Name of the parameter being tested, for use in the exception thrown. [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([ValidatedNotNull]this T value, string name) where T : class { Contract.Requires(value != null,name); } } /// Decorator for an incoming parameter that is contractually enforced as NotNull. [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] public sealed class ValidatedNotNullAttribute : global::System.Attribute {} 

其他细节在我的另一个答案中。

像这样指定ArgumentNullExceptionexception:

 public Bar(Log log) { Contract.Requires(log != null); log.Lines.Add(...); // ... } 

Fxcop期望抛出ArgumentNullExceptionexception……