CodeContracts 中的前提条件和后置条件
如果我写
[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
是后置条件指令,即使我将其调用作为方法的第一行,它也会像最后一行一样在退出函数之前进行验证吗?
If I write
[Pure]
static string s10 {get;set;}
static void Main(string[] args)
{
Contract.Ensures(s10.Length <= 10); //Contract fails
s10 = ";uhlakushdflausgdflasgdfljgaskdjgfasd";
}
As I don't have Premium edition of VS, so no static checking, after run program VS reports me problem: Postcondition failed: s10.Length <= 10
, good.
if I write, instead
[Pure]
static string s10 {get;set;}
static void Main(string[] args)
{
Contract.Requires(s10.Length <= 10); //NullReferenceException
s10 = ";uhlakushdflausgdflasgdfljgaskdjgfasd";
}
VS reports me Null reference exception.
Does it actually mean, that as Ensures
is postcondition dirrective, even if I put its call like a first line of my method, it will be validated like last one, just before exiting the function ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的 - 代码契约重写器将代码以及其他一些内容移动到适当的位置。值得查看 Reflector 中的结果以了解发生了什么。
我强烈建议您仔细阅读代码契约附带的用户指南。据我所知,这是一份很棒的文档。
Yes - the Code Contracts rewriter moves the code around to the appropriate place, as well as a few other things. It's worth looking at the result in Reflector to see what's going on.
I strongly advise you to read the user guide that comes with Code Contracts thoroughly. From what I remember, it's an excellent bit of documentation.