2015-02-08 38 views
1

我的类有两个私有字段和三个构造函数。对于互斥条件的类不变式

一个构造函数是不分配任何值的默认构造函数。

其余构造每个实例化两个领域之一,以确保一个领域是总是null和其他领域是从未null

public class MyClass 
{ 
    private readonly Foo foo; 
    public Foo InstanceOfFoo { get { return this.foo; } } 

    private readonly Bar bar; 
    public Bar InstanceOfBar { get { return this.bar; } } 

    // Default constructor: InstanceOfFoo == null & InstanceOfBar == null 
    public MyClass() 
    { 
    } 

    // Foo constructor: InstanceOfFoo != null & InstanceOfBar == null 
    public MyClass(Foo foo) 
    { 
     Contract.Requires(foo != null); 
     this.foo = foo; 
    } 

    // Bar constructor: InstanceOfFoo == null & InstanceOfBar != null 
    public MyClass(Bar bar) 
    { 
     Contract.Requires(bar != null); 
     this.bar = bar; 
    } 
} 

现在我需要补充的是指定InstanceOfFooInstanceOfBar是互相排斥的一类不变法:既可以null,但只有其中一个可以比null以外的东西。

我该如何在代码中表达?

[ContractInvariantMethod] 
private void ObjectInvariant() 
{ 
    // How do I complete this invariant method? 
    Contract.Invariant((this.InstanceOfFoo == null && this.InstanceOfBar == null) || ...); 
} 

回答

1

看起来简单还是应该enougth:

Contract.Invariant(this.InstanceOfFoo == null || this.InstanceOfBar == null); 

证明(对于某人来说,谁downvoted :)

1. (null, null): true || true -> true 
2. (inst, null): false || true -> true 
3. (null, inst): true || false -> true 
4. (inst, inst): false || false -> false 
+0

你能翻译,为简单易懂的英语?当我尝试总结符合本合同的所有可能配置时,我的脑子很痛。 – 2015-02-08 11:20:01

+0

@StevenLiekens请参阅我的更新与证明表 – 2015-02-08 11:21:45

+0

谢谢!我喜欢你如何布置证明。我需要开始这样做。 – 2015-02-08 11:34:44