开发者

extensions and conflict between decimal & double

i'm not sure if it's just me, but this seems a little weird. I have some extensions in a static class for rounding values:

    public static double? Round(this double? d, int decimals)
    {
        if (d.HasValue)
            return Math.Round(d.Value, decimals, MidpointRounding.AwayFromZero);
        return null;
    }
    public static double? Round(this double d, int decimals)
    {
        return Math.Round(d, decimals, MidpointRounding.AwayFromZero);
    }

i recently added the same for rounding decimals:

    public static decimal? Round(this decimal? d, int decimals)
    {
        if (d.HasValue)
            return Math.Round(d.Value, decimals, MidpointRounding.AwayFromZero);
        return null;
    }
    public static decimal? Round(this decimal d, int decimals)
    {
        return Math.Round(d, decimals, MidpointRounding.AwayFromZero);
    }

i hope no-one can see anything wrong with this, at this point. It appears when i have the code

        var x = (decimal)0;
        var xx = x.Round(0);

the CLR throws the error Member 'decimal.Round(decimal)' cannot be accessed with an instance reference; qualify it with a type name instead

WTF? If i simply rename my decimal rounding extension (for instance call it RoundDecimal), everything works fine. It seems as though the CLR somehow is confusing the double and the decimal methods.. can anyone explain this?

开发者_StackOverflow社区

Interestingly, if I call Round(x, 0) instead, it works fine...


When you call:

var xx = x.Round(0);

The compiler sees this as a call to Decimal.Round, which is an error, since it's a static.

I would strongly recommend using a name for your method that is different than the framework's "Round" methods. For example, in your case, I'd suggest using RoundAwayFromZero. If you did that, you could do:

var xx = x.RoundAwayFromZero(0);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜