[英]Positive to negative number best practices in C#
有2種常見的方法將正數轉換為負數,反之亦然:
var a = -a;
和
var a = (-1)*a;
據我所知,第二是首選,但為什么呢? 還有轉換數字符號(int,float,double等)的其他最佳實踐嗎?
編輯:一元減運算和乘以-1是否有任何區別?
在站點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的代碼更簡單,更短。 那么-a
是更好的方法。
我不明白為什么您會認為第二種方法是首選方法,因為第一種方法要簡單得多,而且我一直都在使用這種方法。 第二種方法也是一種非常普遍的方法,但是由於您希望編寫最少的代碼而沒有使用,但是如果您打算使所有內容都清晰起來,那么我將更喜歡第二種方法。 如果願意,也可以使用Math.abs(x),但我絕對希望使用第一種方法。 如果您想了解有關Math.abs的更多信息,則可以通過Google找到很多教程。 希望這能在某種程度上解決您的問題。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.