扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。
实例:
下面我们定义了一个string类型的扩展方法tointclass,作用是字符串转int,所以下面输出结果应该为7
using System;
namespace ConsoleApp2
{
internal class Program
{
static void Main(string[] args)
{
string a = "6";
string b = "1";
Console.WriteLine(a.ToInttest()+b.ToInttest());
}
}
//必须是静态类才可以添加扩展方法
public static class tointclass
{
//声明扩展方法
//扩展方法必须是静态的
//this 必须有,string表示我要扩展的类型,stringName表示对象名
public static int ToInttest(this string a)
{
return int.Parse(a);
}
}
}
输出结果