1

我在玩微軟的CodeContracts,遇到了一個我無法解決的問題。我有一個有兩個構造函數的類:CodeContracts:如何使用this()調用滿足Ctor的要求?

public Foo (public float f) { 
    Contracts.Require(f > 0); 
} 
public Foo (int i) 
    : this ((float)i) 
{} 

該示例已簡化。我不知道如何檢查第二個構造函數的f是否大於0.這甚至可能與合同有關嗎?

+0

你爲什麼要這麼做?調用這個((float)i)已經檢查f> 0 – chiccodoro 2010-06-18 12:35:29

回答

2

您可以將前提條件添加到第二個構造函數的主體中。

public TestClass(float f) 
{ 
    Contract.Requires(f > 0); 
    throw new Exception("foo"); 
} 
public TestClass(int i): this((float)i) 
{ 
    Contract.Requires(i > 0); 
} 

編輯

嘗試調用上面的代碼:

TestClass test2 = new TestClass((int)-1); 

你會看到,前提是常規異常拋出之前拋出。

+0

我猜你添加的行只有在float構造函數已經被調用後纔會被評估,是嗎? – chiccodoro 2010-06-18 12:38:28

1

我會添加一個靜態方法,將int轉換爲float,並在其中包含Contract.Requires。

class Foo 
{ 
    public Foo(float f) 
    { 
     Contract.Requires(f > 0); 
    } 
    public Foo(int i) 
     : this(ToFloat(i)) 
    { } 

    private static float ToFloat(int i) 
    { 
     Contract.Requires(i > 0); 
     return i; 
    } 
} 

希望這會有所幫助。

相關問題