轉:https://www.cnblogs.com/ScottLin/p/10175513.html
先在StringLibrary類中定義一個靜態方法,如下:
public static class StringLibrary {
//第一個參數指定該方法作用於哪個類型,並且該參數以 this 修飾符爲前綴,當前作用於String類型,也可作用於自定義類型 public static bool StartWithUpper(this String str) { if (String.IsNullOrEmpty(str)) return false; char ch = str[0]; return Char.IsUpper(ch); } }
接着調用:
[TestMethod] public void TestDoesNotStartWithUpper() { string[] words = { "alphabet", "Error", "zebra", "Abc", "αυτοκινητοβιομηχανία", "государство", "1234", ".", ";", " " }; foreach (var word in words) { bool result = word.StartWithUpper(); Assert.IsFalse(result, $"Expected for '{word}': false; Actual:{result}"); } }
具體可參考:C#擴展方法