所有的运算是从右到左进行的,如赋值运算符,要等到其右边的计算出来之后,才把结果放到左边的变量中。 2.清单 1-2. 单目运算符: Unary.cs
using System; class Unary { public static void Main() { int unary = 0; int preIncrement; int preDecrement; int postIncrement; int postDecrement; int positive; int negative; sbyte bitNot; bool logNot; preIncrement = ++unary; Console.WriteLine(\preDecrement = --unary; Console.WriteLine(\postDecrement = unary--; Console.WriteLine(\postDecrement); postIncrement = unary++; Console.WriteLine(\postIncrement); Console.WriteLine(\positive = -postIncrement; Console.WriteLine(\negative = +postIncrement; Console.WriteLine(\bitNot = 0; bitNot = (sbyte)(~bitNot); Console.WriteLine(\logNot = false; logNot = !logNot; Console.WriteLine(\} }
说明
1.当计算表达式的时候,在后置增一和后置减一运算符进行运算时,先返回其值,再进行增一或者减一运算。当使用前置加号和减号运算符进行运算时,是先进行增一或者减一的运算,然后再返回其结果值。
2.在清单1-2中, 变量unary初始化为0,进行++x 运算时,\的值加1,再把其值1赋给\变量。在进行--x运算时,先把\的值减到0, 再把值0赋给\preDecrement\变量。
3.进行x-运算时,先把\的值0赋给\\变量,之后再把\减到-1。进行x++运算时,先把%unary\的值-1赋给\变量,之后再对\\加1,使得\变量现在的值为0。
4.变量\初始值为0,进行按位取反运算,本例中,数0表示为二进制\,按位取反之后变为-1,其二进制表示为\。
5.了解一下表达式\, 任何对类型sbyte, byte, short 或者 ushort 类型数据的运算,返回结果
都是整数。要把值赋给bitNot变量,我们必须使用cast (类型)运算符(强制类型转换),其中Type表示你希望转换成的类型(本例中为sbyte)。 Cast运算符把大范围类型的数据转换为小范围类型的数据时,须特别谨慎,因为此时有丢失数据的危险。一般来说,把小类型的数据赋给大类型变量,并没有问题, 因为大范围数据类型的变量具有足够的空间存放小类型数据。 注意在signed 和unsigned类型之间进行Cast运算时,也存在此类危险。 许多初级程序设计教程对变量的位表示作出了很好的讲解,同时也介绍了直接进行Cast运算的危险。
逻辑非(!)运算符可以处理布尔变量值。本例中,\变量从false 变为true。
上述程序的输出结果如下: >Pre-Increment: 1 >Pre-Decrement 0 >Post-Decrement: 0 >Post-Increment -1 >Final Value of Unary: 0 >Positive: 1 >Netative: -1 >Bitwise Not: -1 >Logical Not: True 3.清单 1-3. 二元运算符 Binary.cs using System; class Binary { public static void Main() { int x, y, result; float floatResult; x = 7; y = 5; result = x+y; Console.WriteLine(\result = x-y; Console.WriteLine(\result = x*y; Console.WriteLine(\result = x/y; Console.WriteLine(\floatResult = (float)x/(float)y;