是否可以指定代码契约以确保该方法不会更改对象的状态
假设我的对象有一个布尔 IsValid
属性。
我想创建一个方法,并确保 IsValid 在调用它之后不会更改,无论调用之前它是 true 还是 false。
有支持这样的事情吗?
Lets say I got a boolean IsValid
property on my object.
I would like to create a method, and ensure that IsValid isn't changed after calling it, whether it was true or false before the call.
Is there a support for such thing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为此,[Pure] 属性已添加到系统中。 Diagnostic.Contracts 命名空间。有关进一步说明,请参阅此处。但是,您无法阻止单个属性被更改。该方法根本不允许更改对象状态(如 C++ const)。
编辑:不幸的是,Pure 属性不适用于当前的工具。我使用以下代码实现了测试,无论是在静态还是在运行时类型检查时都没有错误消息:
关于 纯检查将在“未来”得到支持。无论什么时候(“代码契约团队正在努力解决这个问题,因此在未来的版本中提出了纯度检查器。”)。
我一直在使用该属性,相信它可以正常工作。文档指出,合约中调用的所有方法都必须声明为纯方法。它没有说是否已检查。
所以你的问题的答案是:目前没有对此支持,但将来可能会支持。
For that purpose the [Pure] Attribute has been added to the System.Diagnostic.Contracts Namespace. See here for further explanation. However you cannot prevent a single property from being changed. The method is not allowed to change the object state at all (like the C++ const).
EDIT: Unfortunately the Pure attribute does not work with the current tools. I implemented a test with the following code, no error message either at static nor at runtime type checking:
Regarding to the documentation of Pure checks will be supported 'in the future'. Whenever that is ("The Code Contracts team is working heavy on that, thus to come up with a purity checker in a future release.").
I have been using the attribute in the believe it works properly. The documentation says that all methods called within a contract must be declared as pure. It doesn't say whether that's checked or not.
So the answer to your question is: There is no current support for this, but may be in the future.
我自己没有尝试过,但是根据MSDN
Contract.OldValue
可能有助于检查单个属性值是否未更改:I haven't tried it myself, but according to the MSDN
Contract.OldValue
might help to check that a single property value has not changed:不,不幸的是,c# 不提供 c++ 那样的 const 逻辑。
No, unfortunately c# doesn't provide a const logic such c++ does.
执行此操作的唯一方法是以您知道它不会更改的方式控制您的代码。否则没有特定的代码或语法来控制它(如在 C++ 中)。
The only way to go about doing this is to control your code in such a way that you know it won't change. There is no specific code or syntax to control this otherwise (as in C++).