扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型
本文使用扩展方法来增加string的功能,举一个例子
我们把string类最常用的静态方法IsNullOrEmpty扩展成“实例”方法:
我们平常使用的时候
bool b = string.IsNullOrEmpty(str);
-------扩展方法三要素:静态类、静态方法、this关键字!--------
它们的第一个参数指定该方法作用于哪个类型,并且该参数以
this 修饰符为前缀。
扩展方法:
public static class MyString //静态类
{
public static bool IsNullOrEmpty(this string str) //静态方法、this关键字,他们的第一个参数指定该方法作用于哪个类型,以this修饰符最为前缀
{
return string.IsNullOrEmpty(str);
}
}
有了扩展方法,在使用的时候: static void Main(string[] args)
{
string str1 = "";
string str2 = "aaa";
bool b1 = str1.IsNullOrEmpty();
bool b2 = str2.IsNullOrEmpty();
Console.WriteLine("str1-------" + b1);
Console.WriteLine("str2-------" + b2);
Console.ReadKey();
}
结果: