先在StringLibrary类中定义一个静态方法,如下:



C#扩展方法this_c#

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);
}
}


C#扩展方法this_c#


接着调用:



C#扩展方法this_c#

[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#扩展方法this_c#