gpt4 book ai didi

c# - 确保对象不变?

转载 作者:太空宇宙 更新时间:2023-11-03 11:12:34 24 4
gpt4 key购买 nike

是否有任何方法使用代码契约来确保/检查方法不会更改对象的任何成员,类似于 C++ const 方法或将所有成员设置为 readonly?

即一种比以下更简单的方法:

Contract.Ensures(this.member1 == Contract.OldValue(this.member1));
Contract.Ensures(this.member2 == Contract.OldValue(this.member2));
Contract.Ensures(this.member3 == Contract.OldValue(this.member3));
Contract.Ensures(this.member4 == Contract.OldValue(this.member4));
Contract.Ensures(this.member5 == Contract.OldValue(this.member5));

或使用 Contract.EnsuresOnThrow 相同。

最佳答案

所以本质上,您想要检查该方法是否是 Pureofficial documentation表示它还不支持(见第 5.4 节):

5.4 Purity

All methods called within a contract must be pure: that is, they must not update
any pre-existing state. (A pure method is allowed to modify objects that have been
created after entry into the pure method.) Code Contract tools currently assume
the following things are pure:

* Methods marked [Pure] (If a type is marked [Pure], then that applies to all of
its methods.) The pure attribute is dened in the contract library. (Section 4.3)

* Property getters.

* Operators (static methods whose names start with op , have one or two parameters
and a non-void return type).

* Any method whose fully qualified name begins with
System.Diagnostics.Contracts.Contract, System.String, System.IO.Path, or
System.Type.

* Any invoked delegate, provided that the delegate type itself is attributed with
[Pure]. The existing delegate types System.Predicate<T> and System.Comparison<T>
are considered pure.

In the future, there will be a purity checker that will enforce these assumptions.

关于c# - 确保对象不变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13490353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com