c#扩展方法奇思妙用高级篇四:对扩展进行分组管理2010-04-23 博客园 鹤冲天从系列文章开篇到现在,已经实现的很多扩展了,但过多的扩展会给我们带来很多麻烦,试看下图:

面对这么多“泛滥”的扩展,很多人都会感到很别扭,的确有种“喧宾夺主”的感觉,想从中找出真正想用的方法来太难了!尽管经过扩展后的string类很“强大”,但易用性确很差。很多人因此感觉扩展应适可而止,不该再继续下去...其实这是一种逃避问题的态度,出现问题我们应该主动去解决,而不是去回避!有很多种方法可以解决以上问题,最简单的就是使用将扩展放入不同namespace中,使用时按需using相应namespace,可达到一定效果。但这种方法有很大缺点: 一个命名空间中的扩展若太多同样会让我们的智能提示充斥着扩展方法,扩展太少每次使用都要using多个命名空间,很麻烦。先介绍一种简单的方式,先看效果:

图1中前三个以As开始的三个扩展就是采用分组技术后的三类扩展,分别是中文处理、转换操作、正则操作,后面三个图分别对就这三类扩展的具体应用。图2中的有三个中文处理的扩展ToDBC、ToSBC、GetChineseSpell分别是转为半角、转为全角、获取拼音首字母。通过这样分组后,string类的智能提示中扩展泛滥的现象得到了解决,使用AsXXX,是以字母A开始,会出现在提示的最前面,与原生方法区分开来。采用这种方式有几个缺点:1.使用一个扩展要先As一次,再使用具体扩展,比之前多了一步操作:这是分组管理必然的,建议使用频率非常高的还是直接扩展给string类,不要分组。只对使用频率不高的进行分组。2.扩展后的智能提示不友好,扩展的方法与Equals、ToString混在了一起,而且没有扩展方法的标志。先给出这种方法的实现参考代码,再来改进:
1 public static class StringExtension
2 {
3 public static ChineseString AsChineseString(this string s) { return new ChineseString(s); }
4 public static ConvertableString AsConvertableString(this string s) { return new ConvertableString(s); }
5 public static RegexableString AsRegexableString(this string s) { return new RegexableString(s); }
6 }
7 public class ChineseString
8 {
9 private string s;
10 public ChineseString(string s) { this.s = s; }
11 //转全角
12 public string ToSBC(string input) { throw new NotImplementedException(); }
13 //转半角
14 public string ToDBC(string input) { throw new NotImplementedException(); }
15 //获取汉字拼音首字母
16 public string GetChineseSpell(string input) { throw new NotImplementedException(); }
17 }
18 public class ConvertableString
19 {
20 private string s;
21 public ConvertableString(string s) { this.s = s; }
22 public bool IsInt(string s) { throw new NotImplementedException(); }
23 public bool IsDateTime(string s) { throw new NotImplementedException(); }
24 public int ToInt(string s) { throw new NotImplementedException(); }
25 public DateTime ToDateTime(string s) { throw new NotImplementedException(); }
26 }
27 public class RegexableString
28 {
29 private string s;
30 public RegexableString(string s) { this.s = s; }
31 public bool IsMatch(string s, string pattern) { throw new NotImplementedException(); }
32 public string Match(string s, string pattern) { throw new NotImplementedException(); }
33 public string Relplace(string s, string pattern, MatchEvaluator evaluator) { throw new NotImplementedException(); }
34 }