自动实现属性的代码合约
有什么方法可以将契约放在 .NET 中自动实现的属性上吗? (如果答案是“是”怎么办)?
(我假设使用来自 DevLabs 的 .NET 代码合约)
Is there any way to put contracts on automatically implemented properties in .NET?
(And how if the answer is 'Yes')?
(I assume using .NET code contracts from DevLabs)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这是可能的 - 所需要做的就是将合同条件添加到类中的
[ContractInvariantMethod]
方法中,然后将等效的Requires
前提条件添加到自动条件中set
ter,并将后置条件Ensures
添加到get
中。来自参考的第 2.3.1 节举例来说:
“相当于以下代码:”
Yes, this is possible - all that is needed is to add your contract condition to the
[ContractInvariantMethod]
method in your class, which then adds the equivalentRequires
precondition to the automaticset
ter, and a post conditionEnsures
is added to theget
. From section 2.3.1 of the ReferenceAnd by example:
"Is equivalent to the following code:"
我没有在想,但是您可以轻松地编写可以做到这一点的片段。如果您走此路线,这是一个免费的摘要编辑,这将使任务变得非常容易。
I'm thinking not, but you could easily write a snippet that would do this. If you go this route, here is a free snippet editor that will make the task very easy.
谢谢波吉斯。
我的错误是我实际上使用了
ReleaseRequires
选项,该选项实际上只处理方法的通用版本,Requires
。放在自动实现的属性上的不变式实际上变成了
Requires
前提条件,但它不是通用的 - 这就是为什么它无法使用此选项。该怎么做:
VARIANT 1. 考虑使用代码片段和可爱的
Requires
而不是自动实现的属性 - 这使我们能够使用所需类型的异常。VARIANT 2. 将选项更改为代码契约选项中的
ReleaseRequires
为Preconditions
,并随意在自动属性上编写不变量 -重写器工具会自动将它们更改为Requires
。但是,它们将是非通用的 - 这意味着,如果合同被破坏,将抛出ContractException
并且无法更改此行为。感谢大家的帮助!
Thanks Porges.
My mistake was that I actually used
ReleaseRequires
option, which, indeed, deals only with generic version of the method,Requires<T>
.Invariant which is put on an auto-implemented property is really turned into a
Requires
precondition, but it's not generic - that's why it didn't work using this option.What to do:
VARIANT 1. Consider using code snippets and lovely
Requires<T>
instead of auto-implemented properties - that enables us to use exceptions of desired type.VARIANT 2. Change the option
ReleaseRequires
toPreconditions
in the Code Contracts' options and feel free to write invariants on auto-properties - the rewriter tool will automatically change them into theRequires
. However, they will be non-generic - that means, in case of contract broken, aContractException
will be thrown and there is no way to change this behaviour.Thanks everyone for the help!