C# 扩展方法

扩展方法 使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。

当我们vs中编写代码使用Linq 的时候,经常会看到智能提示出现带如下符号的方法:

这就是扩展方法。

如何定义自己的扩展方法呢?MSDN给出了详细的解释(具体可以参阅 实现和调用自定义扩展方法):

1、定义一个静态类以包含扩展方法。该类必须对客户端代码可见。 
2、将该扩展方法实现为静态方法,并使其至少具有与包含类相同的可见性。
3、该方法的第一个参数指定方法所操作的类型;该参数必须以 this 修饰符开头。
4、在调用代码中,添加一条 using 指令以指定包含扩展方法类的命名空间。
5、按照与调用类型上的实例方法一样的方式调用扩展方法。

下面来举两个小例子来说明一下扩展方法的定义和调用:

1、首先看一个最简单的,来为String 类 定义一个扩展方法: 

 public static class MehtondExtension
    {
        public static string tostring(this string s)
        {
           return (string.Format("Extension output: {0}", s));
        }
    }

注意 类的定义和方法的定义都有static 修饰,方法的第一个参数有 this 修饰符 

在Main函数中进行调用:

class Program
    {
        static void Main(string[] args)
        {
            string s = "Hello World";
            Console.WriteLine(s.ExToString());
            Console.ReadKey();
        }
    }

 结果输出 :Extension output: Hello World 

2、来个略微复杂一点的,我们为一个集合添加一个查询的扩展方法,当然用linq可以更直接,这里举例只是为了说明扩展方法的使用:

//学生类
    public class Student
    {
        public string  Name { get; set; }

        public int Age { get; set; }

        public string City { get; set; }
    }

    //集合类
    public class StudentList:List<Student>
    {
        public StudentList()
        {
            this.Add(new Student() { Name = "张三", Age = 22, City = "北京" });
            this.Add(new Student() { Name = "李四", Age = 23, City = "北京" });
            this.Add(new Student() { Name = "王武", Age = 24, City = "南京" });
            this.Add(new Student() { Name = "何二", Age = 25, City = "南京" });
        }
    }

    //扩展方法
    //根据城市名称返回学生列表
    public static class StuListExtension
    {
        public static IEnumerable<Student> GetStudentByCity(this List<Student> stuList, string city)
        {   
            var result = stuList.Where(s => s.City == city).Select(s => s);
            return result;
        }
    }

 在Main函数中进行调用:

 class Program
    {
        static void Main(string[] args)
        {            
            StudentList StudentSource = new StudentList();
            IEnumerable<Student> bjStudents = StudentSource.GetStudentByCity("北京");
            Console.WriteLine("北京的学生列表:");
            foreach (var s in bjStudents)
            {
                Console.WriteLine(string.Format("姓名:{0}  年龄:{1}  城市:{2}", s.Name, s.Age, s.City));
            }
            Console.ReadKey();
        }
    }

 结果显示:

-=本文源码下载=-

posted @ 2013-04-25 10:07  Rising_Sun  阅读(9620)  评论(2编辑  收藏  举报