我有利用.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
或者我用<
替換<=
時,它會警告我違規。這種不正當行爲僅限於double
和float
。我假設它與浮點值的精度有關。
它甚至當我制定這樣的規定:
Contract.Requires<ArgumentException>(!(0 > value));
那是一個錯誤還是我做錯了什麼?
只是出於興趣,爲什麼你不會允許0作爲有效值? – thumbmunkeys 2014-10-09 10:43:43
我希望允許0作爲有效值。合同應該確保每個值> = 0. – vlow 2014-10-09 10:48:22
絕對有趣,我會嘗試聯繫弗朗切斯科,https://visualstudiogallery.msdn.microsoft.com/1ec7db13-3363-46c9-851f-1ce455f66970 – 2014-10-09 11:40:08