扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。 它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。 扩展方法当然不能破坏面向对象封装的概念,所以只能是访问所扩展类的public成员。
扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。
1.this扩展方法
必须是静态类才可以添加扩展方法 :声明扩展方法的步骤:类必须是static,方法是static
实例1、给string 类型增加一个Add方法,该方法的作用是给字符串增加一个字母a
第一步:声明扩展方法
//声明扩展方法
//扩展方法必须是静态的(是否有参数),Add有三个参数:this 必须有,string表示我要扩展的类型,stringName表示对象名
。
//三个参数this和扩展的类型必不可少,对象名可以自己随意取如果需要传递参数,再增加一个变量即可
public static string Add(this string stringName)//在调用是stringName接受str的值 this string:表示为string添加一个add方法
{
return stringName+"a";
}
第二步:调用扩展方法,必须用对象来调用
Static class Program
{
static void Main(string[] args)
{
string str = "quzijing";
//注意调用扩展方法,必须用对象来调用
string Newstr = str.Add();
Console.WriteLine(Newstr);
Console.ReadKey();
}
实例2、为string扩展一个验证邮件类
(1)、扩展方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
//声明扩展方法的步骤:类必须是static,方法是static,
//第一个参数是被扩展的对象,前面标注this。
//使用扩展方法的时候必须保证扩展方法类已经在当前代码中using
namespace 扩展方法
{
//扩展方法必须是静态的
public static class StringHelper
{
//扩展方法必须是静态的,第一个参数必须加上this
public static bool IsEmail(this string _input)
{
return Regex.IsMatch(_input, @"^\\w+@\\w+\\.\\w+$");
}
//带多个参数的扩展方法
//在原始字符串前后加上指定的字符
public static string Quot(this string _input, string _quot)
{
return _quot + _input + _quot;
}
}
}
(2)、使用方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 扩展方法
{
class Program
{
static void Main(string[] args)
{
string _myEmail = "abc@163.com";
//这里就可以直接使用string类的扩展方法IsEmail了
Console.WriteLine(_myEmail.IsEmail());
//调用接收参数的扩展方法
Console.WriteLine(_myEmail.Quot("!"));
Console.ReadLine();
}
}
}