c# string 常用扩展
string是c#里面最最常用的类,和它的使用频度比起来,它的操作确少的可怜,实例方法只有三十个左右,静态方法只有十多个,远远满足不了我们日常的需求。
本文使用扩展方法来增加string的功能,举出几个例子,也算是抛砖引玉吧!
首先我们把string类最常用的静态方法IsNullOrEmpty扩展成“实例”方法:
C#代码
public static bool IsNullOrEmpty( this string s) { return string .IsNullOrEmpty(s); }下面是调用代码:
C#代码
public static void Test1() { string s = "" ; bool b1 = string .IsNullOrEmpty(s); bool b2 = s.IsNullOrEmpty(); }别小看这一步改进,扩展后可减少我们编写代码的时间,提高我们编码的速度。如你对此怀疑,将第4行和第5行的代码手工录入100次(不能复制粘贴)试试,就知道了!
如果你需要,也可以扩展出“IsNotNullOrEmpty”。
再来看下FormatWith扩展
C#代码
public static string FormatWith( this string format, params object [] args) { return string .Format(format, args); } public static void Test2() { string today = "今天是:{0:yyyy年MM月dd日 星期ddd}" .FormatWith(DateTime.Today); }也很简单的,我们这里简单说一下效率问题,string.Format函数有多个重载:
C#代码
public static string Format( string format, params object [] args); public static string Format( string format, object arg0); public static string Format( string format, object arg0, object arg1); public static string Format( string format, object arg0, object arg1, object arg2); public static string Format(IFormatProvider provider, string format, params object [] args);尽管第1行的Format功能强大到可以取代中间的三个,但它的效率不高。中间三个重载是出于性能的考虑。
如果你比较看重效率的性能,仅仅使用一个FormatWith扩展是不行的,可以参照Format的重载,多扩展上几个!
.Net中处理字符串最强大的还是正则表达式,下面我们将其部分功能扩展至string上:
C#代码
public static bool IsMatch( this string s, string pattern) { if (s == null ) return false ; else return Regex.IsMatch(s, pattern); } public static string Match( this string s, string pattern) { if (s == null ) return "" ; return Regex.Match(s, pattern).Value; } public static void Test3() { bool b = "12345" .IsMatch(@ "\d+" ); string s = "ldp615" .Match( "[a-zA-Z]+" ); }使用Regex要引用命名空间“System.Text.RegularExpressions”。
扩展后,我们就可以直接使用扩展中的方法,而不必再引用这个命名空间了,也不用写出“Regex”了。
Regex的Replace方法也比较常用,也可以扩展到string上。
接下来是与int相关的操作:
C#代码
public static bool IsInt( this string s) { int i; return int .TryParse(s, out i); } public static int ToInt( this string s) { return int .Parse(s); } public static void Test4() { string s = "615" ; int i = 0; if (s.IsInt()) i = s.ToInt(); }同样方法可完成转换到DateTime。
如果你用过CodeSmith,对下面这种应用应该比较熟悉:
C#代码
public static string ToCamel( this string s) { if (s.IsNullOrEmpty()) return s; return s[0].ToString().ToLower() + s.Substring(1); } public static string ToPascal( this string s) { if (s.IsNullOrEmpty()) return s; return s[0].ToString().ToUpper() + s.Substring(1); }不用多解释,大家都能看明白的。
还可扩展出像sql中字符串处理的Left、Right,比较简单,很好实现的。
也可以实现英文名词的单重数形式转换,这个应用场景不大,实现相对麻烦。
作者: Leo_wl
出处: http://www.cnblogs.com/Leo_wl/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
版权信息声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did50825