在自动实现属性code合同属性、合同、code

2023-09-03 16:03:13 作者:‵天屎的翅膀

有什么办法把在.NET自动实现的属性的合同? (以及如何如果答案是是)?

Is there any way to put contracts on automatically implemented properties in .NET? (And how if the answer is 'Yes')?

(我假设使用来自DevLabs .NET code合同)

(I assume using .NET code contracts from DevLabs)

推荐答案

由于Porges。

我的错误是,我实际使用 ReleaseRequires 选项,这,的确,只有通用版本的方法交易,要求< T>

My mistake was that I actually used ReleaseRequires option, which, indeed, deals only with generic version of the method, Requires<T>.

不变它放在一个自动实现的属性的真的变成了 要求 precondition,但它不是通用的 - 这是为什么它没有使用此选项的工作。

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.

怎么做:

VARIANT 1.考虑使用code段和可爱的要求&LT; T&GT; ,而不是自动实现的属性 - 这使我们能够使用所需的例外类型。

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. 更改选项 ReleaseRequires preconditions 在code合同选项,并随便写不变量的自动性能 - 重写工具会自动将它们变成了要求。然而,他们将非通用 - 这意味着,如果合同的打破, ContractEx​​ception 将被抛出,也没有办法改变这种行为

VARIANT 2. Change the option ReleaseRequires to Preconditions in the Code Contracts' options and feel free to write invariants on auto-properties - the rewriter tool will automatically change them into the Requires. However, they will be non-generic - that means, in case of contract broken, a ContractException will be thrown and there is no way to change this behaviour.

感谢大家的帮助!