"合同不能在试块中"是什么意思?

Mat*_*tin 6 c# code-contracts

我正在使用3.5库来进行微软代码合同

public object RetrieveById(int Id)
{    
    //stuff happens...
    Contract.Ensures(newObject != null, "object must not be null");
    return newProject;
    //No error message if I move the Contract.Ensures to here
    //But it isn't asserting/throwing a contract exception here either           
}
Run Code Online (Sandbox Code Playgroud)

我得到编译器消息:"错误18方法'中的try块中的合同部分'Controller.RetrieveById(System.Int32)'

更新:

我在你的帮助下想出来了:

  • 移到顶部
  • 检查Contract.Result

    Contract.Ensures(Contract.Result()!= null,"object不能为null");

Jas*_*ans 6

我可能会遗漏一些东西,但我只是看了一下这个文档:

http://msdn.microsoft.com/en-us/library/dd412865.aspx

它说:

此方法调用必须位于方法或属性的开头,在任何其他代码之前.

因此,只需将Ensures调用放在方法的顶部,就不会出现任何问题.