首先,請原諒任何錯字,英語不是我的母語。在c#4.0中比較近似值?
這是我的問題。我創建表示近似值爲這樣一類:
public sealed class ApproximateValue
{
public double MaxValue { get; private set; }
public double MinValue { get; private set; }
public double Uncertainty { get; private set; }
public double Value { get; private set; }
public ApproximateValue(double value, double uncertainty)
{
if (uncertainty < 0) { throw new ArgumentOutOfRangeException("uncertainty", "Value must be postivie or equal to 0."); }
this.Value = value;
this.Uncertainty = uncertainty;
this.MaxValue = this.Value + this.Uncertainty;
this.MinValue = this.Value - this.Uncertainty;
}
}
我想使用這個類不確定觀測值,這些值如x = 8.31246 +/- 0.0045例如,進行計算。
我想重載此類中的操作符。我不知道如何實現的>,> =,< =和<運營商...我想的第一件事情是這樣的:
public static bool? operator >(ApproximateValue a, ApproximateValue b)
{
if (a == null || b == null) { return null; }
if (a.MinValue > b.MaxValue) { return true; }
else if (a.MaxValue < b.MinValue) { return false; }
else { return null; }
}
然而,在後一種情況下,我由於準確的結果不是'空',所以不滿足於'空'。這可能是'真的',也可能是'假的'。
.net 4中是否有任何對象可以幫助實現這個功能,我不知道或者我正在做正確的方法?我也在考慮使用一個對象而不是布爾值來定義值在哪些情況下優於或不是另一個,而不是實現比較運算符,但是我覺得它對於我想實現的有點太複雜。 。
您不能實現比較,因爲你不具備的比較應該如何工作的規範。寫下管理這種比較的規則。如果你很難提出這樣的規則,這暗示沒有更多的上下文,比較是沒有意義的。 – Jon
@Guillaume:正如一個供參考,在.NET空> null是假的,空與空值的含義。 –
你爲什麼試圖在布爾操作上返回null?我不是你甚至會允許近似值爲空的類型的原因。 –