C#扩展方法

如果处于某种原因,不能在类内部源代码上添加新的方法,那么可以使用扩展方法,如下

//原始类
public class BaseClass
{
    public int Data{get;set;}
}

//扩展方法必须定义在非泛型静态类中
public static class ExtendClass
{
    //扩展方法的第一个参数为要扩展的类,并在前面加this
    public static void Plus(this BaseClass bass, int data)
    {
        bass.Data += data;
    }
}

//客户程序
class Program
{
    static void Main(string[] args)
    {
        //扩展方法与其他方法一样,根据实例调用
        new BaseClass().Plus(10);            
    }
}

 

posted @ 2014-03-17 22:35  kuntaljy  阅读(271)  评论(0编辑  收藏  举报