合同类应该是一个抽象类

时间:2010-09-04 00:48:30

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

以下代码向我发出警告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闭嘴。

我是否遗漏了一些没有警告的编译?

2 个答案:

答案 0 :(得分:9)

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

  

工具期望合同类是抽象的,并实现它提供合同的接口   对

答案 1 :(得分:3)

您引用的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); 
  } 
}

合同类必须是抽象的。