C# 关于字符、字符串和文本处理


Char

在.NET Framework中,字符总是用16位UniCode代码值。

可以使用三种技术实现数值类型和Char实例的相互转换。

  • 强制类型转换

强制类型转换是将一个Char转换成一个数值最简单的办法,这种办法也是效率最高的,编译器会生成中间语言(IL)指令来执行转换,不必调用方法。

Char2int2Char
 1     class Program
2 {
3 static void Main(string[] args)
4 {
5 char c;
6 int i;
7 c = (char)97;
8 Console.WriteLine(c);
9 Console.ReadLine();
10
11 i = (int)c;
12 Console.WriteLine(i);
13 Console.ReadLine();
14 c = Convert.ToChar(65);
15 Console.WriteLine(c);
16 Console.ReadLine();
17
18 }
19 }

相应的IL代码为:

Char2Int2Char
 1 .method private hidebysig static void  Main(string[] args) cil managed
2 {
3 .entrypoint
4 // 代码大小 54 (0x36)
5 .maxstack 1
6 .locals init ([0] char c,
7 [1] int32 i)
8 IL_0000: nop
9 IL_0001: ldc.i4.s 97
10 IL_0003: stloc.0
11 IL_0004: ldloc.0
12 IL_0005: call void [mscorlib]System.Console::WriteLine(char)
13 IL_000a: nop
14 IL_000b: call string [mscorlib]System.Console::ReadLine()
15 IL_0010: pop
16 IL_0011: ldloc.0
17 IL_0012: stloc.1
18 IL_0013: ldloc.1
19 IL_0014: call void [mscorlib]System.Console::WriteLine(int32)
20 IL_0019: nop
21 IL_001a: call string [mscorlib]System.Console::ReadLine()
22 IL_001f: pop
23 IL_0020: ldc.i4.s 65
24 IL_0022: call char [mscorlib]System.Convert::ToChar(int32)
25 IL_0027: stloc.0
26 IL_0028: ldloc.0
27 IL_0029: call void [mscorlib]System.Console::WriteLine(char)
28 IL_002e: nop
29 IL_002f: call string [mscorlib]System.Console::ReadLine()
30 IL_0034: pop
31 IL_0035: ret
32 } // end of method Program::Main

其中可以由 IL代码看出,第24行多了一次ToChar的函数调用。

String

String在C#中被视为基元类型。

常用的构造方法为:

String
1         static void Main(string[] args)
2 {
3 string s = "Hi xuanxing";
4 Console.WriteLine(s);
5 Console.ReadLine();
6 }

相应的IL代码为:

String
 1 .method private hidebysig static void  Main(string[] args) cil managed
2 {
3 .entrypoint
4 // 代码大小 21 (0x15)
5 .maxstack 1
6 .locals init ([0] string s)
7 IL_0000: nop
8 IL_0001: ldstr "Hi xuanxing"
9 IL_0006: stloc.0
10 IL_0007: ldloc.0
11 IL_0008: call void [mscorlib]System.Console::WriteLine(string)
12 IL_000d: nop
13 IL_000e: call string [mscorlib]System.Console::ReadLine()
14 IL_0013: pop
15 IL_0014: ret
16 } // end of method Program::Main

由IL第8行代码可以看出 CLR用一种特殊的方式来构造常量字符串.(ldstr),不需要进行对象的构造。但是对于重载后的"+"操作符,如果对于字符串变量进行操作,就会产生多个字符串对象,这样会浪费堆内存,降低执行效率,是应该避免的。

在需要大量字符串连接等操作的时候可以选用System.Text.StringBuilder类来进行,产生的实例要少一些,更省内存,效率更高些。

 




 

posted @ 2011-10-11 23:16  璇星  阅读(435)  评论(0编辑  收藏  举报