您的位置:首页 > 编程语言 > C#

C#2008新特性--(扩展方法)Extension Method

2008-07-04 10:54 531 查看
扩展方法可以向已经编译好的类中注入其他方法。

方法是:将需要扩展的类声明为static类中的Static方法。它的第一个参数是针对何种类型,要加入this关键字。

有了这个特性,你可以写自己的通用类库支持多种扩张。比如验证类。。。

示例:

using System;

using System.Collections;

using System.Linq;

using System.Text;

using System.Collections.Generic;

using System.Runtime.Serialization;

namespace TestCS

{

    //必须是静态的类

    static class MyExtension

    {

        //必须是静态的方法。且参数列表中含有 this

        public static void  DisplayToString(this object o)

        {

            Console.WriteLine(o.ToString());

        }

        public static void Foo(this int i)

        {

            Console.WriteLine("Calling Foo {0}", i);

        }

        public static void Foo(this int i, string msg)

        {

            Console.WriteLine("Calling Foo {0}, {1}", i, msg);

        }

    }

    static class CarExtense

    {

        public static void SlowDown(this Car c,int delta)

        {

            c.CurrentSpeed-=delta;

            Console.WriteLine("Car is slowing dow..... at a speed of {0}", c.CurrentSpeed);

        }

    }

    

    class Program

    {

        static void Main(string[] args)

        {

            //实例引用

            //值类型

            int myInt = 343;

            myInt.DisplayToString();

            myInt.Foo("xx");

           

            //实例引用

            //引用类型

            System.Data.DataSet ds = new System.Data.DataSet();

            ds.DisplayToString();

            //静态引用

            MyExtension.DisplayToString(myInt);

            MyExtension.Foo(myInt);

            //Car的应用

            Car c = new Car("pet",200);

            c.Accelerate(100);

            c.SlowDown(100);

            

        }

    }

  

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐