扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。 它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀
定义静态类中的静态(扩展)方法:
public static class Extension
{
public static int ToInt(this string str)
{
int val;
int.TryParse(str, out val);//这里当转换失败时返回的val为0
return val;
}
}
使用上述扩展方法:
static void Main(string[] args)
{
string str = "23";
int i = str.ToInt();
Console.WriteLine(i);
Console.ReadKey();
}
运行: