扩展String类

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

 1 None.gif using  System;
 2 None.gif
 3 None.gif public   class  StringEx
 4 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 5InBlock.gif    public static string ProperCase(string s)
 6ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 7InBlock.gif        s = s.ToLower();
 8InBlock.gif        string sProper = "";
 9InBlock.gif        
10ExpandedSubBlockStart.gifContractedSubBlock.gif        char[] seps = new char[]dot.gif{' '};
11InBlock.gif        foreach(string ss in s.Split(seps))
12ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
13InBlock.gif            sProper += char.ToUpper(ss[0]);
14InBlock.gif            sProper += (ss.Substring(1,ss.Length - 1+ ' ');
15ExpandedSubBlockEnd.gif        }

16InBlock.gif        return sProper;
17ExpandedSubBlockEnd.gif    }

18ExpandedBlockEnd.gif}

19 None.gif
20 None.gif class  StringExApp
21 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
22InBlock.gif    static void Main(string[] args)
23ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
24InBlock.gif        string s = Console.ReadLine();
25InBlock.gif        Console.WriteLine("初始字符串为:\t{0}",s);
26InBlock.gif        
27InBlock.gif        string t = StringEx.ProperCase(s);
28InBlock.gif        Console.WriteLine("转化以后的字符串为:\t{0}",t);
29ExpandedSubBlockEnd.gif    }

30ExpandedBlockEnd.gif}

这是一段简单的代码,只是提供一个思路,为我们以后扩展封闭类提供一种选择。




参考资料:《C#技术内幕》
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值