1.扩展方法的定义,即介绍

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace 扩展方法
{
/// <summary>
/// 1.扩展方法必须放到静态类中
/// 2.方法必须是静态方法
/// 3.方法的第一个参数是指明为哪个类声明扩展方法,切以this开头
///
/// 特点
/// 1.扩展方法优先级低于实例方法
/// 2.扩展方法可以与实例方法构成重载
/// 3.定义在父类上面的扩展方法,在子类对象上可以使用 (即:为一个类定义一个扩展方法,那么这个类的子类对象也是可以使用这个扩展方法的)
/// 4.定义在接口上的扩展方法,在子类(实现类)对象上可以使用
/// </summary>
public static class ExpandHelper //这个类叫什么都无所谓,我仅仅是在这个类中为某个类扩展的方法
{
//为DateTime类扩展一个不带参数,具有一个string类型返回值的方法,这个扩展方法的方法名叫ExcpandMethod,它后面那个括号里的 this DateTime dateTime 并不是参数,而是指明为DateTime这个类扩展方法,所以这个扩展方法是一个没有参数,有一个string类型返回值的扩展方法。
public static string ExcpandMethod(this DateTime dateTime)
{
return dateTime.ToString("yyyy-MM-dd HH:mm:ss");
}
//为DateTime类扩展一个带两个参数,具有一个int类型返回值的方法,这个扩展方法的方法名叫Sum,它后面那个括号里的 this DateTime dateTime 并不是参数,而是指明为DateTime这个类扩展方法, a,和b 则分别是这Sum方法的两个参数
public static int Sum(this DateTime dt, int a, int b)
{
return a + b;
}
//注意:因为string类中本身就有一个ToUpper() 实例方法,这个实例方法本身是不带参数,那现在我们又来扩展一个同名且不带参数的ToUpper()方法,这个方法实际上是不起作用的,因为实例方法的优先级比我们自己扩展的方法的优先级高,所以当我们调用这个ToUpper()方法的时候,调用的是实例方法。无法调用这个扩展方法。
public static string ToUpper(this string str) //----此方法无效
{
return str.ToUpper();
}
//那我们就想给string类扩展一个有效的ToUpper方法怎么办呢? 答案是:我们可以给ToUpper这个方法扩展一个重载方法。这样是可以的。
//注意:因为string类型本身有一个名为ToUpper且不带参数的方法,现在我们给string类型扩展一个ToUpper带一个参数的重载方法。
public static string ToUpper(this string str, int a)
{
return str.ToUpper() + a;
}
//为object这个类定义一个不带参数的扩展方法,这个方法有一个string类型的返回值。
//因为Object类是所有类的父类,所以所有的类都是可以使用这个aaa扩展方法的
public static string aaa(this object obj)
{
return "大家好!";
}
public static string bbb(this IList list)
{
return "中国,你好!";
}
}
}
2.扩展方法的使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace 扩展方法
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DateTime dt = DateTime.Now;
string datetime = dt.ExcpandMethod();
Response.Write(datetime); //打印出:2015-10-28 23:12:05
int sum= dt.Sum(5, 6);
Response.Write(sum); //打印出:11
string str = "abc";
string newstr = str.ToUpper(5);
Response.Write(newstr); //打印出:ABC5
Response.Write(Response.aaa()); //打印出:大家好! 因为我为object这个方法扩展了一个aaa 方法,又因为object是所有类的父类,我为父类扩展的aaa方法,它的子类也可以使用它。
List<string> list = new List<string>();
string s= list.bbb();
Response.Write(s); //打印出:中国,你好! 因为我为Ilist这个接口扩展了一个bbb方法,而List<>这个泛型类是实现了Ilist这个接口的。所以List<>对象list是可以使用bbb这个扩展方法的。
}
}
}