C#中一些很基础但有经常导致错误的一些概念
char 的双重身份
char表示字符但却被看成是整数家族的一部分,它所表示的值是一个无符号整数,它可以参加计算,并可以隐式转换成int,long,ushort,uint和ulong
我看一下下面的例子就明白了:
1
using System;
2![]()
3
public class Characters
4
{
5
public static void Main()
6
{
7
char firstSymbol;
8
char secondSymbol;
9
int intFirstSymbol;
10
int intSecondSymbol;
11
int result;
12![]()
13
firstSymbol = '\u0034';
14
secondSymbol = '\u0039';
15![]()
16
Console.WriteLine("firset as charactor:{0}",firstSymbol);
17
Console.WriteLine("SecondSymbol as Charactor:{0}",secondSymbol);
18
intFirstSymbol = firstSymbol;
19
intSecondSymbol = secondSymbol;
20
Console.WriteLine("firstSymbol as int:{0}",intFirstSymbol);
21
Console.WriteLine("SecondSymbol as int:{0}",intSecondSymbol);
22
result = firstSymbol + secondSymbol;
23
Console.WriteLine("result as int:{0}",result);
24
Console.WriteLine("result as character:{0}",(char)result);
25
}
26
}
运行结果:
using System;2

3
public class Characters4
{5
public static void Main()6
{7
char firstSymbol;8
char secondSymbol;9
int intFirstSymbol;10
int intSecondSymbol;11
int result;12

13
firstSymbol = '\u0034';14
secondSymbol = '\u0039';15

16
Console.WriteLine("firset as charactor:{0}",firstSymbol);17
Console.WriteLine("SecondSymbol as Charactor:{0}",secondSymbol);18
intFirstSymbol = firstSymbol;19
intSecondSymbol = secondSymbol;20
Console.WriteLine("firstSymbol as int:{0}",intFirstSymbol);21
Console.WriteLine("SecondSymbol as int:{0}",intSecondSymbol);22
result = firstSymbol + secondSymbol;23
Console.WriteLine("result as int:{0}",result);24
Console.WriteLine("result as character:{0}",(char)result);25
}26
}
\u0034为字符4的Unicode值,\u0039为字符‘9’的Unicode值。
关于“++ --”操作符 放在操作数的前面和后面的区别
很多人都会认为 “++ --” 操作符放在变量的前后是没有区别的,看下面这段代码:
1
using System;
2![]()
3
class PlusPlus
4
{
5
public static void Main()
6
{
7
int a=5;
8
int b=10;
9![]()
10
Console.WriteLine("a++ = {0}",a++);
11
Console.WriteLine("++b = {0}",++b);
12
}
13
}
运行结果:
using System;2

3
class PlusPlus4
{5
public static void Main()6
{7
int a=5;8
int b=10;9

10
Console.WriteLine("a++ = {0}",a++);11
Console.WriteLine("++b = {0}",++b);12
}13
}a++ = 5
++b = 11
在代码中我们把操作符“++”分别放在变量“a”和变量“b”的前面和后面,但是输出的结果却是不同的,放在后面的a变量输出的结果没事使a变量增加,而操作符放在前面的b变量却自动增加了,一般我们都不会注意到这点,以至于我们在程序中出现了这样的错误我们都找不到原因,这是因为操作符“++ --”如果放在变量的后面是在整个表达式完成运算以后才会自增1,而放在放在前面则是先自增以后再参与表达式的运算。



浙公网安备 33010602011771号