Contract.Immutable in Object Invariants [英] Contract.Immutable in Object Invariants

查看:92
本文介绍了Contract.Immutable in Object Invariants的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,
很高兴有一个b

Hello,

it would be very great to have a

Contract.Immutable<T>([bool condition, ]T property) 


可以在Invariant-Method中使用(甚至可以在"普通"成员中使用)。

这会导致像添加一样a

that can be used within the Invariant-Method (and maybe even within "ordinary" members).

This would cause the same like adding a

if (condition)
     Contract.Ensures(Contract.OldValue(property) == property);

$ b $ *在每个成员的末尾*除了*构造函数。
这个,以及Contract.OldValue<T>在ObjectInvariants中总是默认(T)使用

at the end of each member *except* Constructors.
This, and the issue described in Contract.OldValue<T> in ObjectInvariants is always default(T) make using

Contract.Invariant(!condition || Contract.OldValue(property) == property)


不可能。

这个条件对于"Freezables"来说很重要。这意味着在特殊事件之后只能是不可变的对象(例如方法调用)。

最后一件事是可以应用于字段/属性的ImmutableAttribute。

最好的问候是winSharp93

impossible.

The condition would be important for "Freezables" that means objects which are only immutable after a special event (e.g. a method call).

The last thing would be an ImmutableAttribute that can be applied on fields / properties.

Best regards
winSharp93

推荐答案

嗯,为什么不使用readonly关键字? readonly字段可以在构造函数中设置,但是在创建对象时没有其他方法。这正是你想要的。
此外,选择加入或选择退出不变性是一项基本的语言设计决定,并且(在我看来)不应成为Code Contracts库的一部分,该库明确地以DbC原则为目标。例如,Spec#包含用于处理可变性的语言结构,但这与合同没有直接联系。

正如我所说:readonly应该是你的选择:-)

〜马蒂亚斯

Hm, why don't you use the readonly keyword? readonly fields can be set in the constructor, but in no other method when the object has been created. It's exactly what you want.
Furthermore, opt-in or opt-out immutability is a basic language design decision and should (in my opinion) not become part of the Code Contracts library, which clearly aims on the DbC principle. For example, Spec# included language constructs for handling mutability, but this had no direct connections to the contracts.

But as I said: readonly should be your choice :-)

~ Matthias


这篇关于Contract.Immutable in Object Invariants的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆