C# 4.0 中的合约

发布于 2024-07-13 02:34:38 字数 154 浏览 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

李白 2024-07-20 02:34:38

这不是 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.

千笙结 2024-07-20 02:34:38

我非常确定 C# 4.0 中的代码契约内容将在运行时发生,而不是编译时,并且您需要在调用中实际指定条件。 假设你的 Vector3 类有一个 Length 属性,你最终会得到这样的结果:

Expects(vector3.Length == 1);

这实际上会在某种后编译步骤中进行一些 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:

Expects(vector3.Length == 1);

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文