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

扩展方法可以向已经编译好的类中注入其他方法。

方法是:将需要扩展的类声明为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);

            

        }

    }





  

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值