C#擴展方法:string常用擴展
string是c#里面最最常用的類,和它的使用頻度比起來,它的操作確少的可憐,實例方法只有三十個左右,靜態(tài)方法只有十多個,遠遠滿足不了我們?nèi)粘5男枨蟆?/P>
本文使用c#擴展方法來增加string的功能,舉出幾個例子,也算是拋磚引玉吧!
首先我們把string類最常用的靜態(tài)方法IsNullOrEmpty擴展成“實例”方法:
- public static bool IsNullOrEmpty(this string s)
- {
- return string.IsNullOrEmpty(s);
- }
下面是調(diào)用代碼:
- public static void Test1()
- {
- string s = "";
- bool b1 = string.IsNullOrEmpty(s);
- bool b2 = s.IsNullOrEmpty();
- }
別小看這一步改進,擴展后可減少我們編寫代碼的時間,提高我們編碼的速度。如你對此懷疑,將第4行和第5行的代碼手工錄入100次(不能復(fù)制粘貼)試試,就知道了!
如果你需要,也可以擴展出“IsNotNullOrEmpty”。
再來看下FormatWith擴展
- 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函數(shù)有多個重載:
- 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上:
- 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”。
擴展后,我們就可以直接使用c#擴展方法,而不必再引用這個命名空間了,也不用寫出“Regex”了。
Regex的Replace方法也比較常用,也可以擴展到string上。
接下來是與int相關(guān)的操作:
- 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();
- }
同樣方法可完成轉(zhuǎn)換到DateTime。
如果你用過CodeSmith,對下面這種應(yīng)用應(yīng)該比較熟悉:
- 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,比較簡單,很好實現(xiàn)的。
也可以實現(xiàn)英文名詞的單重數(shù)形式轉(zhuǎn)換,這個應(yīng)用場景不大,實現(xiàn)相對麻煩。
c#擴展方法中對string的擴展遠不只這些,根據(jù)你的實際需要,只要用起來方便,就可以擴展出來。
本文只是拋磚引玉,如果大家有實用比較好的對string的擴展,不要吝惜,寫在回復(fù)中,和大家一起分享!
【編輯推薦】