.NET 小数.求负 vs 乘以 -1
decimal.Negate(myDecimal)
和 myDecimal * -1
之间有什么区别(除了可读性之外)吗?
Are there any differences between decimal.Negate(myDecimal)
and myDecimal * -1
(except maybe readability)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我怀疑
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.)
如果您使用 .NET Reflector 查看 .NET 源代码,您将看到以下内容:
(喝咖啡直到它最终打开......)
由于十进制内部的工作方式,看起来这是一种表示 -1 的奇特方式。
如果您执行 *-1 ,它会将其映射到以下调用:
这可能会产生不同的 IL 代码。
If you look in the .NET source with .NET Reflector, you will see the following:
(getting coffee until it finally opens..)
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:
which will likely produce different IL code.
就我个人而言,我发现
-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.来自 MSDN,
decimal.Negate
< /a>:尽管可读性很重要,但实际上没有区别。
From MSDN,
decimal.Negate
:No practical difference then, though readability is important.