因为.Net Framework中的String类是封闭的,所以我们不能从它进行派生来扩展它的功能。
虽然String类已经提供了很多有用的方法来让我们进行字符串的处理和操作,但是有时候一些特殊的的要求还是不能能到满足。
一个例子就是:假如有一个因为句子,比如:“how are you”,我们需要把每个单词的首字母都改成大写,当然人工改写很大一篇文章是很费力的,但是我们查阅.Net Framework中的String类,又没有满足我们需要的处理方法,那么我们就需要自己想办法扩展字符串的功能。
既然不能派生,那么我们就写一个含有我们需要的方法的类,把这个方法设为静态方法就可以使用了。
代码如下:
1
using System;
2
3
public class StringEx
4

{
5
public static string ProperCase(string s)
6
{
7
s = s.ToLower();
8
string sProper = "";
9
10
char[] seps = new char[]
{' '};
11
foreach(string ss in s.Split(seps))
12
{
13
sProper += char.ToUpper(ss[0]);
14
sProper += (ss.Substring(1,ss.Length - 1) + ' ');
15
}
16
return sProper;
17
}
18
}
19
20
class StringExApp
21

{
22
static void Main(string[] args)
23
{
24
string s = Console.ReadLine();
25
Console.WriteLine("初始字符串为:\t{0}",s);
26
27
string t = StringEx.ProperCase(s);
28
Console.WriteLine("转化以后的字符串为:\t{0}",t);
29
}
30
}

2

3

4



5

6



7

8

9

10



11

12



13

14

15

16

17

18

19

20

21



22

23



24

25

26

27

28

29

30

这是一段简单的代码,只是提供一个思路,为我们以后扩展封闭类提供一种选择。
参考资料:《C#技术内幕》