我寫了一個快速的c#擴展方法,但不知道是否有更乾淨的方式來完成我想要做的事情。它確實有效,但是使用字符串轉發器感覺有點冒險,並插入一個小數。C#/ TSQL小數邊界檢查 - 有更清晰的方法嗎?
目標是在應用程序級別,我們可以在發送到數據庫之前清除/修復任何數據問題以防止溢出。
注意:PCL庫,在這種情況下無法引用DLL的外部。
public static bool TsqlDecimalBoundariesCheck(this decimal valueToCheck, int precision, int scale)
{
if(scale > precision) throw new ArgumentException($"BOUNDARY CHECK: Scale [{scale}] must not be higher than Percision [{precision}]");
// create X precision values of the value 9
var precisionValue = new string('9', precision);
// Insert the decimal place x positions from the right
if (scale > 0)
{
precisionValue = precisionValue.Insert((precision - scale), ".");
}
// Get the upper and lower values
var upperBoundry = decimal.Parse(precisionValue);
var lowerBoundry = upperBoundry * -1;
return (valueToCheck <= upperBoundry) && (valueToCheck >= lowerBoundry);
}
而且一些快速的單元測試陪它:
[TestMethod]
public void TestBoundryConstraints()
{
var precision = 4;
var scale = 1;
var testValue = 1000m;
var result = testValue.TsqlDecimalBoundariesCheck(precision , scale);
Assert.IsFalse(result, $"Value {testValue} is expected to be outside Decimal({precision }, {scale})");
testValue = -1000m;
result = testValue.TsqlDecimalBoundariesCheck(precision , scale);
Assert.IsFalse(result, $"Value {testValue} is expected to be outside Decimal({precision }, {scale})");
testValue = 100m;
result = testValue.TsqlDecimalBoundariesCheck(precision , scale);
Assert.IsTrue(result, $"Value {testValue} is expected to be within Decimal({precision }, {scale})");
testValue = 999.9m;
result = testValue.TsqlDecimalBoundariesCheck(precision , scale);
Assert.IsTrue(result, $"Value {testValue} is expected to be within Decimal({precision }, {scale})");
testValue = -999.9m;
result = testValue.TsqlDecimalBoundariesCheck(precision , scale);
Assert.IsTrue(result, $"Value {testValue} is expected to be within Decimal({precision }, {scale})");
}
的'1000m'測試是重複的,你typo'd'precision'一致。 :) – xxbbcc
請參閱http://stackoverflow.com/a/4438489/714151 – MrZander
謝謝..是的,可怕的拼寫..因爲大多數開發人員,據我瞭解。謝謝你的收穫。爲什麼VS還沒有添加拼寫檢查;) – TravisWhidden