[英]Positive to negative number best practices in C#
There are 2 common ways to convert positive number to negative and vice versa: 有2种常见的方法将正数转换为负数,反之亦然:
var a = -a;
and 和
var a = (-1)*a;
Second is preferred, as I know, but why? 据我所知,第二是首选,但为什么呢? And is there any other best practice in converting the sign of the number (int, float, double, etc.) ? 还有转换数字符号(int,float,double等)的其他最佳实践吗?
EDIT: is there any difference in unary minus operation and multiplication to -1 ? 编辑:一元减运算和乘以-1是否有任何区别?
On site http://tryroslyn.azurewebsites.net/ you can see code generated by compiler. 在站点http://tryroslyn.azurewebsites.net/上,您可以看到编译器生成的代码。
And for: 对于:
using System;
public class C {
public int M() {
int a = -2;
a = -a;
return a;
}
public int M1() {
int a = 3;
a = (-1) * a;
return a;
}
}
Compiler generates: 编译器生成:
.class private auto ansi '<Module>'
{
} // end of class <Module>
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig
instance int32 M () cil managed
{
// Method begins at RVA 0x2050
// Code size 4 (0x4)
.maxstack 8
IL_0000: ldc.i4.s -2
IL_0002: neg
IL_0003: ret
} // end of method C::M
.method public hidebysig
instance int32 M1 () cil managed
{
// Method begins at RVA 0x2058
// Code size 8 (0x8)
.maxstack 2
.locals init (
[0] int32
)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: ldc.i4.m1
IL_0003: ldloc.0
IL_0004: mul
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ret
} // end of method C::M1
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x206c
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method C::.ctor
} // end of class C
As you see code for method M i much simplier and shorter. 如您所见,方法M的代码更简单,更短。 Then
-a
is better way. 那么
-a
是更好的方法。
I don't understand why you think that the second would be the preferred method as the first one is a lot simpler and I use this method all the time. 我不明白为什么您会认为第二种方法是首选方法,因为第一种方法要简单得多,而且我一直都在使用这种方法。 The second method is also a very common one but is not used as you would want to write the least amount of Code, but if you are planning to make everything clear... then I would prefer the Second method.
第二种方法也是一种非常普遍的方法,但是由于您希望编写最少的代码而没有使用,但是如果您打算使所有内容都清晰起来,那么我将更喜欢第二种方法。 You could also use Math.abs(x) if you wanted to but I would definitely prefer the first method.
如果愿意,也可以使用Math.abs(x),但我绝对希望使用第一种方法。 If you want to find out more about Math.abs, then you can find a lot of tutorials through google.
如果您想了解有关Math.abs的更多信息,则可以通过Google找到很多教程。 Hope this resolved your question in a way.
希望这能在某种程度上解决您的问题。 :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.