ReSharper和Code Contracts都可以使用的常见PureAttribute是什么?

10

我正在使用ReSharper 8.0和VS2012编写.NET 4.0的C#代码。

ReSharper包含一个属性:JetBrains.Annotations.PureAttribute。这用于提供“未使用纯方法的返回值”检查。

Code Contracts包括一个属性:System.Diagnostics.Contracts.PureAttribute。代码合同检查使用它来确保调用不会产生可见的状态更改,因此不需要重新检查对象的状态。

目前,为了获得这两个工具的功能,必须对方法进行注释以使用每个属性。更糟糕的是,因为它们共享相同的类型名称,所以您需要限定每个属性。

[Pure]
[Jetbrains.Annotations.Pure]
public bool isFinished() {
    ...
为了避免这种情况,应该采取以下三种方法之一:
  1. 编写一个被ReSharper和Contracts都能识别的占位符
  2. 让ReSharper识别Contracts属性
  3. 让Contracts识别ReSharper属性
这些方法中有哪些是可行的?
2个回答

8

3
System.Diagnostics.Contracts.PureAttribute 定义时使用了 [Conditional("CONTRACTS_FULL")]。这意味着,除非使用完整的运行时合同检查构建,否则 ReSharper 将无法看到它,而这并不总是理想的选择。 - Varon
啊,发现得好。这意味着 ReSharper 在编译后的方法上看不到 PureAttribute,除非在编译时定义了 CONTRACTS_FULL。然而,ReSharper 仍然可以在源代码中看到它 - ReSharper 只查看属性的名称,而不是任何条件设置。 - citizenmatt
看起来 R# 9.2 忘记了如何解释 System.Diagnostics.Contracts.PureAttribute :) - porges

2

第三种方法提供了解决方案:Jetbrains.Annotations.PureAttribute被Contracts认可。

然而,当在您的代码中使用Contracts和PureAttribute时,仍会遇到名称冲突问题。这可以通过使用语句来简化:using RPure = Jetbrains.Annotation.PureAttribute;

以下是一些演示属性成功地与Contracts和ReSharper配合使用的代码。

public class StatefulExample {

    public int value { get; private set; }

    public StatefulExample() { value = 1; }

    //Example method that would need to be annotated
    [Jetbrains.Annotations.PureAttribute]
    public int negativeValue() { return -value; }

    public static void useSpecificState(StatefulExample test) {
        Contract.Requires(test.value == 1);
    }

    // ---

    public static void pureMethodRequirementDemonstration() {
        StatefulExample initialState = new StatefulExample();
        useSpecificState(initialState);

        StatefulExample possiblyChangedState = new StatefulExample();
        //"Return value of Pure method is not used" here if annotated.
        possiblyChangedState.negativeValue();

        // "Requires unproven: test.value == 1" if NOT annotated.
        useSpecificState(possiblyChangedState);
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接