zoukankan      html  css  js  c++  java
  • 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#扩展方法


    不积跬步无以至千里,不积小流无以成江海。。。
  • 相关阅读:
    指针、字符串、数组操作
    字符串转换为数字(str2int)
    新的,开始。
    Hello, World.
    Go语言趣学指南lesson1
    hdoj2058
    poj2378
    hdoj1233
    poj2398
    hdoj1392
  • 原文地址:https://www.cnblogs.com/ScottLin/p/10175513.html
Copyright © 2011-2022 走看看