属性不变不正确地应用于支持字段。 [英] property invariant incorrectly applied to backing field.
问题描述
代码合同(1.4.5109.0)似乎没有注意到以下代码中的空引用异常。我的简短调查似乎表明,如果从getter设置了一个字段,那么应用于该属性的任何不变量也适用于该字段。
Code contracts (1.4.5109.0) doesn't seem to notice the null reference exception in the following code. My brief investigations seem to indicate that if a field is set from the getter, then any invariant applied to the property also applies to the field.
public class Functastic
{
public int Get()
{
return foo.GetHashCode();
}
object Foo
{
get { return foo ?? (foo = new object()); }
}
object foo;
[ContractInvariantMethod]
void ObjectInvariant()
{
Contract.Invariant(Foo != null);
}
}
推荐答案
不变量旨在提供针对私有州的全局内部后置条件,因此它们通常应用于字段,而不是属性。 将不变量视为在每种方法中定义相同的后置条件。
Invariants are intended to provide global internal post-conditions against private state, thus they are typically applied to fields, not properties. Think of an invariant as defining the same post-condition in every method.
如果您打算在 Foo 上定义后置条件,那么只需定义一个
的后置条件 Foo 。
If your intention was to define a post-condition on Foo, then simply define a post-condition on Foo.
object Foo
{
get
{
Contract.Ensures(Contract.Result<object>() != null);
return foo ?? (foo = new object());
}
}
请注意,您可以为自动属性定义不变量,因为没有其他方法可以为它们定义公共后置条件,但这不是一回事。 在以下示例中,不变量实际上定义了 Foo 上的公共后置条件
,但仅仅因为 Foo 是自动属性并且是
public 。
Note that you can define invariants for automatic properties simply because there's no other way to define public post-conditions for them, but it's not the same thing. In the following example, the invariant actually defines a public post-condition on Foo, but only because Foo is an automatic property and is public.
public object Foo { get; private set; }
[ContractInvariantMethod]
void ObjectInvariant()
{
Contract.Invariant(Foo != null);
}
- 戴夫
这篇关于属性不变不正确地应用于支持字段。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!