.NET 小数.求负 vs 乘以 -1

发布于 2024-09-13 07:38:14 字数 94 浏览 3 评论 0原文

decimal.Negate(myDecimal)myDecimal * -1 之间有什么区别(除了可读性之外)吗?

Are there any differences between decimal.Negate(myDecimal) and myDecimal * -1 (except maybe readability)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

孤君无依 2024-09-20 07:38:14

我怀疑 Negate 存在,因为有一元减运算符 (op_UnaryNegation),并且最好使用表示等效功能的方法,以便不支持运算符重载的语言仍然可以获得相同的结果。

因此,与其将其与 myDecimal * -1 进行比较,不如将其视为编写 -myDecimal 的替代方式可能会有所帮助。

(我相信它也经过了优化 - 考虑到浮点的工作方式,取负值比普通乘法简单得多;只需翻转一点即可。无需执行任何实际算术。)

I suspect Negate exists because there's a unary minus operator (op_UnaryNegation), and it's good practice to have methods representing the equivalent functionality so that languages which don't support operator overloading can still achieve the same result.

So instead of comparing it with myDecimal * -1 it may be helpful to think of it as being an alternative way of writing -myDecimal.

(I believe it's also optimised - given the way floating point works, negating a value is much simpler than normal multiplication; there's just a bit to flip. No need to perform any actual arithmetic.)

晨与橙与城 2024-09-20 07:38:14

如果您使用 .NET Reflector 查看 .NET 源代码,您将看到以下内容:
(喝咖啡直到它最终打开......)

public static decimal Negate(decimal d)
{
    return new decimal(d.lo, d.mid, d.hi, d.flags ^ -2147483648);
}

由于十进制内部的工作方式,看起来这是一种表示 -1 的奇特方式。

如果您执行 *-1 ,它会将其映射到以下调用:

FCallMultiply(ref result, yourNumber, -1M);

这可能会产生不同的 IL 代码。

If you look in the .NET source with .NET Reflector, you will see the following:
(getting coffee until it finally opens..)

public static decimal Negate(decimal d)
{
    return new decimal(d.lo, d.mid, d.hi, d.flags ^ -2147483648);
}

Looks like this is a fancy way to say -1 due to the way decimal internally works.

If you do *-1 it maps it to the following call:

FCallMultiply(ref result, yourNumber, -1M);

which will likely produce different IL code.

故笙诉离歌 2024-09-20 07:38:14

就我个人而言,我发现 -myDecimal 比任何一个都更具可读性(我不是数学极客,但我很确定这三个都是等效的),但话又说回来,我通常更喜欢紧凑的表示法。

如果是这样,我会选择 Negate,因为我喜欢避免在代码中出现幻数,虽然使用的 -1 并不是真正的幻数,但它看起来确实如此乍一看就像一个。

Personally, I find -myDecimal to be more readable than either (I'm no math geek, but I pretty sure all three are equivalent), but then again, I generally prefer compact notation.

If that is out, I'd go with Negate since I like to avoid magic numbers floating around in my code, and while the -1 as used there isn't really a magic number, it sure looks like one at first glance.

一曲爱恨情仇 2024-09-20 07:38:14

来自 MSDN,decimal.Negate< /a>:

返回指定的 Decimal 值乘以负一的结果。

尽管可读性很重要,但实际上没有区别。

From MSDN, decimal.Negate:

Returns the result of multiplying the specified Decimal value by negative one.

No practical difference then, though readability is important.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文