开发者

Can one make Code Analysis understand Code Contracts?

When using Code Analysis and Code Contracts in combination, I get a lot of warnings like

CA1062: Microsoft.Design : In externally visible method 'Foo.Bar(Log)', validate parameter 'log' before using it.

In Foo.Bar, I have a contract that validates log.

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

Is there a way to make FxCop understand code 开发者_开发技巧contracts?


No I do not think it's possible in the current build as the code generated by the contracts rewriter does not produce the standard pattern that FxCop is looking for.

Typically though I disable this particular FxCop rule when using code contracts. I find the static verifier more than makes up for the loss of this rule as it will yell about a lack of checking much more aggressively than FxCop. I would suggest the same approach here which will fix this problem for you.


Yes, as noted in my answer here, as of version 4.5.2 of the framework (possibly 4.5) it is possible to inform Code Analysis of the Code Contracts being enforced. An extension method and a marker attribute class must be defined like this:

  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 {}

Additional details are in my other answer.


Specify the ArgumentNullException exception like this:

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

Fxcop expects to to throws the ArgumentNullException exception...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜