C# 4.0 中的合约
如果我有一个 Vector3.Normalize()
方法指定后置条件,其中生成的 Vector3
的长度为 1,编译器将如何在编译时检查这一点时间(或之前)? 它是否只是将随机 Vector3
变量传递给该方法?
If I have a Vector3.Normalize()
method that specifies a post condition where the resultant Vector3
is gonna have a length of 1, how would the compiler check for this at compile time (or before)? Does it just pass a random Vector3
variable to the method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是 C# 4.0 的功能。 它是 CLR 4.0 的一个独立于语言的功能,在 IL 级别工作。 它确实具有一定的执行静态检查的能力,但并非适用于每种情况。 它实际上会分析普通编译器为您使用的任何语言生成的 IL,找到您在代码中放入的约束,然后查看代码以确定它是否满足合同。 静态检查(至少在我见过的演示中)是一个可选功能。
This isn't a feature of C# 4.0. It's a language-independent feature of CLR 4.0 that works at the IL level. It does have some ability to perform static checking, but not for every kind of condition. It actually analyzes the IL generated by the normal compiler for whatever language you're using, finds the constraints you put in the code and then looks at the code to figure out if it is going to meet the contract. The static checking (at least in demos I've seen) is an optional feature.
我非常确定 C# 4.0 中的代码契约内容将在运行时发生,而不是编译时,并且您需要在调用中实际指定条件。 假设你的 Vector3 类有一个 Length 属性,你最终会得到这样的结果:
这实际上会在某种后编译步骤中进行一些 IL 重写,最终基本上将方法的主体包装在 try..finally 中其中后置条件测试位于finally 块中。
I'm pretty sure the code contracts stuff in C# 4.0 will happen at runtime, not compile time, and that you would need to actually specify the condition in the call. Supposing your Vector3 class has a Length property, you would end up with something like this:
Which would actually hit some IL rewriting during a sort of post-compilation step which would end up essentially wrapping the body of the method in a try..finally where the post condition test is in the finally block.