扩展方法与链式编程

如:string s; s.ToUper().ToString();这个就是扩展方法的形式(可以一级一级的调)   那么,我们自己怎么来写扩展方法呢?

(1)、在类的前面加上static关键字
(2)、在方法的第一个参数前面加上this关键字(这样在使用这个方法的时候就不用在后面的括号中传参,而是用s.的方式来调用这个方法)
(注意这个是.NET3.0的新特性,所以低版本的Vs没法实现)
(3)、方法的第一个参数必须是你要扩展的那个类型,比如你要给int扩展一个方法,那么第一个参数就必须是int。

 

如果想要在低版本的vs中也实现链式编程,看下面的一个例子

 

using System;

using System.Collections.Generic;

using System.Text;

 

namespace 链式编程

{

    class Program

    {

        static void Main(string[] args)

        {

            Person p1 = new Person();

            p1.Name = "名人李四";

            p1.Run().Sing().Swim();

            Console.Read();

        }

    }

    class Person

    {

        private string name;

        public string Name

        {

            get { return name; }

            set { name = value; }

        }

        public Person Run()

        {

            Console.WriteLine("Run");

            return this;

        }

        public Person Swim()

        {

            Console.WriteLine("Swim");

            return this;

        }

        public Person Sing()

        {

            Console.WriteLine("Sing");

            return this;

        }

    }

}

 

 

posted @ 2012-04-06 12:32  伯箫  阅读(219)  评论(0编辑  收藏  举报