C#的扩展方法(this)

先在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#扩展方法

猜你喜欢

转载自www.cnblogs.com/ScottLin/p/10175513.html