开发者

Convert from Price

Im attempting to Convert a Price (from an API (code below)).

public class Price
{
    public Price();
    public Price(double data);
    public Pric开发者_JAVA技巧e(double data, int decimalPadding);
}

What I would like to do is compare the price from this API to a Double. Simply trying to convert to Double isnt working as I would have hoped.

Double bar = 21.75;
Price price = new Price();

if (Convert.ToDouble(price) >= bar) {
//code
}

when I try something like this, I believe it says the value must be lower than infinity.

How can I convert this price so they can be compared?


Convert.ToDouble cannot magically convert a Price object to a double, unless Price implements IConvertible.


You would need a property in your price object that returns the double and compare that.


You could use an implicit operator to convert to double. This is as per the MSDN for "implicit" operator in C#.

E.g.

class Price
{
    public static implicit operator double (Price d)
    {
        return d.data;
    }
    public static implicit operator Price (double d)
    {
        return new Price(d);
    }
}

Alternatively, for your comparisons, implement IComparable<double> and IEquatable<double> on your Price class then use the CompareTo instead and/or another operator overload.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜