CodeContracts中的前提条件和后置条件

时间:2011-08-05 18:07:23

标签: c# code-contracts

如果我写

 [Pure]
 static string s10 {get;set;}

 static void Main(string[] args)
 {
     Contract.Ensures(s10.Length <= 10); //Contract fails
     s10 = ";uhlakushdflausgdflasgdfljgaskdjgfasd";
 }

由于我没有VS的高级版,所以没有静态检查,运行后程序VS报告我问题:Postcondition failed: s10.Length <= 10,好。

如果我写,而不是

 [Pure]
 static string s10 {get;set;}

 static void Main(string[] args)
 {
    Contract.Requires(s10.Length <= 10); //NullReferenceException
    s10 = ";uhlakushdflausgdflasgdfljgaskdjgfasd";
 }

VS报告我空引用异常。

这实际上意味着,因为Ensures是后置条件dirrective,即使我把它的调用放在我的方法的第一行,它会像退出函数一样在最后一行之前验证吗?

1 个答案:

答案 0 :(得分:3)

是 - Code Contracts重写器将代码移动到适当的位置,以及其他一些东西。值得查看Reflector中的结果,看看发生了什么。

强烈建议您仔细阅读代码合同附带的用户指南。从我记忆中来看,它是一个很好的文档。

相关问题