您的位置:首页 > 其它

扩展方法

2015-08-27 23:18 183 查看
扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。 它们的第一个参数指定该方法作用于哪个类型,并且该参数以 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();
}


运行:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: