2014-10-09 37 views
12

我有利用.NET代碼契約一個非常簡單的類:爲什麼靜態分析忽略雙重<= and > =要求?

public class ContractSquareRoot 
{ 
    /// <summary> 
    /// Makes your life much easier by calling Math.Sqrt for you. Ain't that peachy. 
    /// </summary> 
    /// <param name="value">The value to calculate the square root from. No negatives!</param> 
    /// <returns>The square root of the given value. Obviously always > 0.</returns> 
    public double CalculateSquareRoot(double value) 
    { 
     Contract.Requires<ArgumentException>(0 <= value); 
     Contract.Ensures(0 <= Contract.Result<double>()); 

     double squareRoot = Math.Sqrt(value); 

     return squareRoot; 
    } 
} 

當我打電話與負值的方法,我預計靜態代碼分析警告我一下吧。

class Program 
{ 
    static void Main(string[] args) 
    { 

     var barMansSquareroot = new ContractSquareRoot(); 

     // This should not be possible... 
     barMansSquareroot.CalculateSquareRoot(-42); 

    } 
} 

但即使Contract.Requires失敗拋出所需的異常,靜態代碼分析標誌着一切論斷是正確的。有趣的是,當我將值類型更改爲int或者我用<替換<=時,它會警告我違規。這種不正當行爲僅限於doublefloat。我假設它與浮點值的精度有關。

它甚至當我制定這樣的規定:

Contract.Requires<ArgumentException>(!(0 > value)); 

那是一個錯誤還是我做錯了什麼?

+0

只是出於興趣,爲什麼你不會允許0作爲有效值? – thumbmunkeys 2014-10-09 10:43:43

+0

我希望允許0作爲有效值。合同應該確保每個值> = 0. – vlow 2014-10-09 10:48:22

+2

絕對有趣,我會嘗試聯繫弗朗切斯科,https://visualstudiogallery.msdn.microsoft.com/1ec7db13-3363-46c9-851f-1ce455f66970 – 2014-10-09 11:40:08

回答

1

我希望你可能錯過了安裝微軟代碼合同。

您可以從微軟研究院下載Microsoft代碼契約:http://research.microsoft.com/en-us/projects/contracts/

現在在你的項目屬性,你會得到一個額外的標籤,您可以設置運行時和靜態檢查。

+0

請參閱此處瞭解更多詳情https://www.develop.com/csharpcodecontracts – Joseph 2014-10-27 08:59:49

+0

Joseph,我正確安裝了Code Contracts。正如您在我的問題中所看到的,代碼合同通常工作,並且在上述特定情況下無法工作。 – vlow 2015-01-15 00:32:17

相關問題