大家都知道StringBuilder是處理字符串的首選,我不太明白為什么StringBuilder提供的方法竟然比string類要少,挺奇怪。
廢話不多說,直接圖文跟着走吧。
上圖先(我寫好的拓展方法):
默認StringBuilder是沒有IndexOf方法的,這里IndexOf方法是我自己拓展上去的。
如何來實現這個拓展呢,代碼如下:
using System; using System.Collections.Generic; using System.Text; namespace ExtensionMethod { public static class StringBuilderExtension { /// <summary> /// 這是我自己寫的StringBuilder的拓展方法 /// </summary> /// <param name="sb">StringBuilder字符串類型</param> /// <param name="value">要檢索的值</param> /// <returns></returns> public static int IndexOf(this StringBuilder sb, char value) { for (int i = 0; i < sb.Length; i++) { if (sb[i] == value) return i; } return -1; } } }
注意看方法結構里面的第一個參數,加了個this,這樣就表示為StringBuilder的拓展方法了。
另外要注意的地方:拓展方法是在.NET 3.5以上版本才支持的,需要組件System.Core
如果你的項目版本已經調整至3.5以上,無需引入這個System.Core組件,項目會默認帶上它的。
附上Demo源碼項目:http://files.cnblogs.com/andrew-blog/ExtensionMethod.rar