C#原始类型扩展方法—this参数修饰符

语法格式: 

  public static class StringText
    {
        public static string[] WorkSplit(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries);
        }

        public static string[] WorkSplit2(String str)
        {
            return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries);
        }
    }

  其中WorkSplit方法是能被字符串对象调用的,而WorkSplit2方法不能被调用,原因为参数值;

调用代码:

 string[] arr = s.WorkSplit();
            
            foreach (string item in arr)
            {
                Console.WriteLine(item);
            }

  

 

解说:

     扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。对于用 C# 和 Visual Basic 编写的客户端代码,调用扩展方法与调用在类型中实际定义的方法之间没有明显的差异。

  扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。仅当您使用 using 指令将命名空间显式导入到源代码中之后,扩展方法才位于范围中。

posted @ 2012-07-04 09:39  hejiyong  阅读(104)  评论(0)    收藏  举报