C# 什么是;合同可以';“不要在试块中”;什么意思?

C# 什么是;合同可以';“不要在试块中”;什么意思?,c#,code-contracts,C#,Code Contracts,我正在使用microsoft代码合同的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

我正在使用microsoft代码合同的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           
}
我得到编译器消息: “错误18方法'Controller.RetrieveById(System.Int32)'中try块内的协定节”

更新:

我在你的帮助下找到了答案:

  • 上台
  • 对照合同检查结果

    Contract.surveures(Contract.Result()!=null,“对象不能为null”)


我可能遗漏了什么,但我只是查看了相关文档:

它说:

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


因此,只需将surevers调用保留在方法的顶部,您就不会遇到任何问题。

这里有一个类似的解决方案:

您最近的编辑显示您在
合同上方有代码。确保
语句。
合同。确保
必须位于方法中任何其他代码之前,因此:

public object RetrieveById(int Id)
{    
    //first line of method:
    Contract.Ensures(newObject != null, "object must not be null");

    //stuff happens...

    return newProject;        
}

它非常简单:Contract类通过抛出异常来表示违反了合同。将其放在try块中无法达到目的,您可能会捕获异常。

您可以发布整个方法内容吗。另外-
Contract。确保在任何方法中
必须是第一行代码。返回语句后的代码将e遥不可及。这就是为什么把它移到那里没有任何作用。