2016-03-24 110 views
-1

有亦然2种常见的方式来转换正数负和副负数最佳实践:积极在C#

var a = -a; 

var a = (-1)*a; 

其次是首选,因为我知道,但为什么?在转换数字符号(int,float,double等)方面还有其他的最佳做法吗?

编辑:一元减法运算和乘法运算有没有区别?

+7

什么让你觉得第二个是首选?似乎对我非常混乱。请注意,既不会天真地期望如果'a'是'int.MinValue' /'long.MinValue' ... –

+1

我认为你的意思是'int a = 1'和'a = -a'类似的东西。 – J3soon

+0

我的意思是任何数字...所以乔恩Skeet - 你是对的,但你不建议任何正确的版本,并没有回答我的问题 –

回答

4

现场http://tryroslyn.azurewebsites.net/您可以看到编译器生成的代码。

并为:

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; 
    } 
} 

编译器生成:

.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 

正如你看到的子程序M我更simplier和更短的代码。 然后-a是更好的方法。

+0

ohh,谢谢!这就是我想要的! –

0

我不明白你为什么认为第二种方法是首选方法,因为第一种方法简单得多,而且我始终使用这种方法。第二种方法也是一种非常常见的方法,但没有使用,因为您希望编写最少量的代码,但如果您打算将所有内容都清除干净,那么我宁愿使用第二种方法。 你也可以使用Math.abs(x)如果你想,但我肯定会喜欢第一种方法。如果你想了解更多关于Math.abs的信息,那么你可以通过google找到很多教程。 希望通过某种方式解决了您的问题。 :)