3.6 StringHelper類
StringHelper類是最大的輔助類之一,估計它是我寫的第一個輔助類,因為針對字串的處理操作非常多,很容易就可以想到一些方法來改善效能,更容易地處理字串列表,輸出字串資料等等。
看一下StringHelper類的結構圖(3-9所示),您會發現它的方法非常多,重載的方法支援很多不同類型的參數。它還包含大量的單元測試,前面您就曾見過一個。
圖3-9
您可能會問為什麼這個類中的方法那麼多,而單元測試卻那麼少。這是因為很多年前我就開始寫這個類了,而那個時候還沒開始使用單元測試。其中有些方法現在在.Net 2.0 Framework中已經被實現了,所以它們也就沒有太大的意義,不過我還是習慣於使用自己寫的方法,我只是希望其中的某些方法對您能有所協助。要想熟練使用這麼多的方法的確需要一些時間,不過當您發現某個方法可以滿足您進行一項複雜的字串操作時,您或許會感謝我(當然也可能是感謝您自己,如果您有自己的輔助類的話)。
提取檔案名稱
在System.IO命名空間的Path類中,也包含一些類似GetDirectory、CutExtension的方法,不過StringHelper類中用來處理檔案名稱的最有用的方法之一就是ExtractFilename,它去掉了檔案的路徑名和副檔名,僅僅剩下檔案的名字。Path類中的GetFileNameWithoutExtension方法也可以做類似的操作,不過出於某些原因我還是更喜歡自己的方法。如果您想實現自己的方法,並需要一些實際的工作代碼,這會很有趣。再強調一次:您不必自己寫Path類中已經存在的方法,除非您不知道Framwork中已經提供了,或者您想自己去研究一下。
我已經很久沒有測試StringHelper類中方法的處理效能了,不過我猜大多數方法的處理速度要比Path類中的快得多。
/// <summary>
/// Extracts filename from full path+filename, cuts off extension
/// if cutExtension is true. Can be also used to cut of directories
/// from a path (only last one will remain).
/// </summary>
static public string ExtractFilename(string pathFile, bool cutExtension)
{
if (pathFile == null)
return "";
// Support windows and unix slashes
string[] fileName = pathFile.Split(new char[] { '\\', '/' });
if (fileName.Length == 0)
{
if (cutExtension)
return CutExtension(pathFile);
return pathFile;
} // if (fileName.Length)
if (cutExtension)
return CutExtension(fileName[fileName.Length - 1]);
return fileName[fileName.Length - 1];
} // ExtractFilename(pathFile, cutExtension)
給這樣的方法寫單元測試也很簡單,使用下面的代碼來檢查輸出的結果是否在正確:
Assert.AreEqual("SomeFile",
StringHelper.ExtractFilename("SomeDir\\SomeFile.bmp"));
輸出資料行表
StringHelper類中另一個比較特殊的方法是WriteArrayData,它把像列表、數組以及IEnumerable資料輸出為文本字串,這樣它們就可以被寫入記錄檔中。它的實現也非常簡單:/// <summary>
/// Returns a string with the array data, ArrayList version.
/// </summary>
static public string WriteArrayData(ArrayList array)
{
StringBuilder ret = new StringBuilder();
if (array != null)
foreach (object obj in array)
ret.Append((ret.Length == 0 ? "" : ", ") + obj.ToString());
return ret.ToString();
} // WriteArrayData(array)
列表和泛型列表都是從ArrayList類繼承而來的,所以可以給這個方法傳遞動態清單類型。另外,對於Array類型、特殊的集合類型、byte和integer數群組類型以及IEnumerable類型也都存在對應的重載版本,不過使用非參考型別的重載操作速度會更快。
可以使用下面的代碼來測試WriteArrayData方法:
/// <summary>
/// Test write array
/// </summary>
// [Test]
public void TestWriteArray()
{
Assert.AreEqual("3, 5, 10",WriteArrayData(new int[] { 3, 5, 10 }));
Assert.AreEqual("one, after, another",
WriteArrayData(new string[] { "one", "after", "another" }));
List<string> genericList = new List<string>();
genericList.Add("whats");
genericList.AddRange(new string[] { "going", "on" });
Assert.AreEqual("whats, going, on",
WriteArrayData(genericList));
} // TestWriteArray()