【问题标题】:Contract class should be an abstract class合约类应该是一个抽象类
【发布时间】:2010-09-04 00:48:30
【问题描述】:

以下代码给了我警告Contract class 'FooContracts' should be an abstract class。从我在线阅读的所有示例(例如http://www.infoq.com/articles/code-contracts-csharp)来看,这应该可以工作(可能没有编译器警告)。

[ContractClass(typeof(FooContracts))]
public interface IFoo {
  void Bar(string foo);
}

[ContractClassFor(typeof(IFoo))]
internal sealed class FooContracts : IFoo {
  void IFoo.Bar(string foo) {
    Contract.Requires(foo != null);
  }
}

我在 Visual Studio 2010 中,在项目属性的 Code Contracts 部分中具有以下设置:

  • 执行运行时契约检查(设置为Full
  • 执行静态合同检查(在Static Checking 下)
  • 在后台检查

我还定义了 CONTRACTS_FULL 编译符号来让 ReSharper 闭嘴。

我是否遗漏了一些东西来使这个编译没有警告?

【问题讨论】:

    标签: c#-4.0 abstract-class code-contracts


    【解决方案1】:

    code contracts manual 的第 2.8 节明确指出它应该是一个抽象类:

    这些工具期望合约类是抽象的并实现它提供合约的接口 为。

    【讨论】:

    • 嗯。感谢您的链接。我发现的任何示例代码中都没有提到或演示过这一事实。
    【解决方案2】:

    您引用的 InfoQ 文章很可能是不正确的。它基于深度 C# 的“早期访问”版本,因此代码协定的实现可能在章节/文章最初编写和 .NET 4 发布之间发生了变化。

    以下代码应该可以工作:

    [ContractClass(typeof(FooContracts))] 
    public interface IFoo { 
      void Bar(string foo); 
    } 
    
    [ContractClassFor(typeof(IFoo))] 
    internal abstract class FooContracts : IFoo { 
      void IFoo.Bar(string foo) { 
        Contract.Requires(foo != null); 
      } 
    }
    

    合约类必须是抽象的。

    【讨论】:

    • 但是将类抽象化意味着在实现接口后你不能再新建它了
    • @MnemonicFlow 你不应该创建合约类的实例。它仅供代码合同引擎使用。
    猜你喜欢
    • 2010-10-27
    • 2013-08-23
    • 2019-09-05
    • 2016-02-28
    • 2022-10-07
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多