码迷,mamicode.com
首页 > Web开发 > 详细

.net 扩展方法

时间:2016-07-20 01:06:24      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:

扩展方法其实就是为现有类型增加一个扩展方法,现有类型可以是int、string、datetime这几种基本类型,也可以是自定义类型。

能够增加扩展类有一个前提是:被增加的扩展类必须是一个静态类。

此外,扩展方法必须是一个静态方法。所以调用扩展方法直接用扩展类的类名调用。

比如为string类增加一个扩展方法:ToInt

public static class ExtendsString

{

  public static int ToInt(this string str)

  {

    int id;

    int.TryParse(t,out id);

    return id;

  }

}

由上述代码可见,扩展方法接受一个自身参数this,类型为string,并且this string必须放在方法参数的第一个位置。

 

.net 扩展方法

标签:

原文地址:http://www.cnblogs.com/lz-blog/p/5686778.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!