“合约不能位于 try 块中”是什么意思?意思是?
我正在使用 3.5 库来执行 microsoft 代码合约,
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
}
我收到编译器消息: “方法‘Controller.RetrieveById(System.Int32)’中 try 块内的错误 18 Contract 部分
更新:
在您的帮助下我找到了答案:
- 移至顶部
检查 Contract.Result
Contract.Ensures(Contract.Result() != null, "对象不能为 null ");
I'm using the 3.5 library for microsoft code contracts
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
}
I get the compiler message:
"Error 18 Contract section within try block in method 'Controller.RetrieveById(System.Int32)'
UPDATE:
I figured it out with your help:
- Move to top
Check against Contract.Result
Contract.Ensures(Contract.Result() != null, "object must not be null ");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我可能遗漏了一些东西,但我只是查看了相关文档:
http: //msdn.microsoft.com/en-us/library/dd412865.aspx
它说:
因此,只需将 Ensures 调用保留在方法的顶部,您就不应该遇到任何问题。
I might be missing something, but I just looked at the documentation for this:
http://msdn.microsoft.com/en-us/library/dd412865.aspx
it says:
So just leave the Ensures call at the top of the method and you should not get any problems.
这非常简单:Contract 类通过抛出异常来发出违反合同的信号。将其放在 try 块中就达不到目的,您很容易捕获异常。
It's pretty simple: the Contract class signals contract violations by throwing an exception. Putting it in a try block defeats the purpose, you're liable to catch the exception.
这是一个类似的解决方案:
http:// /social.msdn.microsoft.com/Forums/en/codecontracts/thread/43f467f1-14b7-4e56-8030-50f842b7ba68
您最近的编辑显示您的代码位于
Contract.Ensures
语句之上。Contract.Ensures
必须位于方法中的任何其他代码之前,因此:Here's a similar solution:
http://social.msdn.microsoft.com/Forums/en/codecontracts/thread/43f467f1-14b7-4e56-8030-50f842b7ba68
Your recent edit shows you have code above the
Contract.Ensures
statement.Contract.Ensures
must come before any other code in your method, so: