当前位置: 移动技术网 > IT编程>开发语言>c# > C#中的扩展方法详解

C#中的扩展方法详解

2019年07月18日  | 移动技术网IT编程  | 我要评论
扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。

扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。 以上是msdn官网对扩展方法的描述,现在我通过一个情景例子来对此进行阐释。假设一个控制台程序class program{}里面的主函数如下:

static void main(string[] args)
    {
      datetime now = datetime.now;
      string time = now.tostring("yyyy-mm-dd hh:mm:ss"); 
      console.writeline(time);
      console.readkey();
    }

假设需求变了,日期的显示格式要变成"yyyy-mm-dd"这种格式,当然只需要初始化time时按下面写法改写即可:

string time = now.tostring("yyyy-mm-dd");
但是如果要改变日期格式的有很多个类呢?每个都要改一次吗?这样一旦需求变来变去就忙死人了。传统的解决方式是封装一个帮助类,在里面写方法,然后供其他类调用。

本例在当前项目模仿添加一个datehelper类:public class datehelper{},在类里面定义方法:

public static string datetostring(datetime dt)
    {
      return dt.tostring("yyyy-mm-dd hh:mm:ss");
    }

于是原来的主函数改写如下:

static void main(string[] args)
    {
      datetime now = datetime.now;
      string time = datehelper.datetostring(now);
      console.writeline(time);
      console.readkey();
    }

此时如果变需求,只需要改写datehelp类里的datetostring()方法就行了,不管有多少个类调用此方法,都会被影响。问题解决了,可是这样要调用另一个类的方法,还是有点麻烦,有没有什么方法能够让我们像now.datetostring()一样直接调用呢?当然datetime是微软写好的,我们改不了,无法创建想要的实例方法,于是,便引出了扩展方法。
下面是扩展方法的要素:

1.此方法必须是一个静态方法

2.此方法必须放在静态类中

3.此方法的第一个参数必须以this开头,并且指定此方法是扩展自哪个类型

根据以上要素,我们datehelper类改成静态类:public static class datehelper{} ,同时改写datetostring()方法:

public static string datetostring(this datetime dt)
    {
      return dt.tostring("yyyy-mm-dd hh:mm:ss");
    }

此时回到主函数方法体,输入"now."便可以看见自动提示有个datetostring()方法,于是代码可以这样写:

static void main(string[] args)
    {
      datetime now = datetime.now; 
      string time = now.datetostring();
      console.writeline(time);
      console.readkey();
    }

显而易见,这样用起来会更加便捷,而且这样让我们看起来确实就像是被扩展类型本身具有的实例方法一样,可读性很高。下面概括一下扩展方法的特点:

1.扩展方法扩展自哪个类型,就必须是此类型的变量来使用,其他类型无法使用,本例扩展自datetime类型,就只能是被datetime类型的变量.出来(now.datetostring())
2.扩展方法中的this后面的参数不属于方法的参数,本例是无参数,this后面的datetime dt是指明扩展方法扩展自何种类型
3.如果扩展方法和实例方法具有相同的签名,则优先调用实例方法
4.扩展自父类上的方法,可以被子类的对象直接使用
5.扩展自接口上的方法,可以被实现类的对象直接使用
6.扩展方法最终还是被编译器编译成:静态类.静态方法(),本例中now.datetostring()最终还是会被编译成datehelper.datetostring(now),这是它的本质

实际上,我们可能会遇到这样的情景,如在接口扩展一个方法的时候,所有的原本已实现该接口的类都要实现新扩展的方法,这样的改动是一个很麻烦的工作,可以使用扩展方法“曲线救国”;而有时候我们想为某个类添加新方法却不想改动这个类,那么扩展方法这种“伪添加”方法的方式就体现出它的价值了。最常见的扩展方法是linq标准查询运算符,运用广泛,这种方便快捷的方式理应博得码农们点1024个赞。

“扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。”

这是msdn上说的,也就是你可以对string,int,datarow,datatable等这些类型的基础上增加一个或多个方法,使用时不需要去修改或编译类型本身的代码。

先做个例子吧,以string为例,需要在字符串类型中加一个从字符串转为数值的功能。

以往我们可能是这样做的,会专门写一个方法做过转换

public static int strtoint(string s)
{
  int id;
  int.tryparse(s, out id);//这里当转换失败时返回的id为0
  return id;
}

调用就使用

string s = "abc";
int i = strtoint(s);

若是string类型有一个名为toint()(从字符串转为数值)的方法,就可以这样调用了

string s = "abc";
int i = s.toint();

这样看起来是不是更好,下面来看看具体怎么实现吧

第一步:

我先创建一个解决方案,一个web应用程序(webtest)及一个类库(w.common)

在webtest项目添加引用w.common项目

第二步:在类库中新建一个名为estring.cs类

using system;
using system.collections.generic;
using system.linq;
using system.text;
 
namespace w.common
{
  public static class estring
  {
    /// <summary>
    /// 将字符串转换为int
    /// </summary>
    /// <param name="t"></param>
    /// <returns>当转换失败时返回0</returns>
    public static int toint(this string t)
    {
      int id;
      int.tryparse(t, out id);//这里当转换失败时返回的id为0
      return id;
    }
  }
}


看了上面的代码了吧,扩展方法规定类必须是一个静态类,estring是一个静态类,里面包含的所有方法都必须是静态方法。

msdn是这样规定扩展方法的:“扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。 它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。”

estring里有一个toint的静态方法,他接收一个自身参数this,类型为string,this string必须在方法参数的第一个位置。

这句话什么意思,即你需要对string扩展一个toint方法,this是string实例化后的对象,这可能说的不太清楚,我的表述能力能弱,不要见怪呀。。。通俗的说就是,扩展方法跟静态类的名称无关,只需要在一个静态类里面定义一个静态方法,第一个参数必须this string开头。

如果需要你要对datetime类型扩展方法名为isrange(判断是否在此时间范围内),代码如下:

/// <summary>
  /// 此时间是否在此范围内 -1:小于开始时间 0:在开始与结束时间范围内 1:已超出结束时间
  /// </summary>
  /// <param name="t"></param>
  /// <param name="starttime"></param>
  /// <param name="endtime"></param>
  /// <returns></returns>
  public static int isrange(this datetime t, datetime starttime, datetime endtime)
  {
    if (((starttime - t).totalseconds > 0))
    {
      return -1;
    }
 
    if (((endtime - t).totalseconds < 0))
    {
      return 1;
    }
 
    return 0;
  }


这里的扩展方法是用this datetime打头,那么就可以这样调用

time.isrange(t1,t2);//判断时间time是否在t1到t2的范围内
当前代码在使用扩展方法前需要先引用命名空间

using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.ui;
using system.web.ui.webcontrols;
using w.common;//这里引用扩展方法所在的命名空间
 
namespace webtest
{
  public partial class _default : system.web.ui.page
  {
    protected void page_load(object sender, eventargs e)
    {
      use1();
      response.write("<br />");
      use2();
    }
 
    /// <summary>
    /// 没有用扩展方法
    /// </summary>
    private void use1()
    {
      string s = "abc";
      int i = strtoint(s);
      response.write("没有用扩展方法:" + i);
    }
 
    /// <summary>
    /// 使用扩展方法
    /// </summary>
    private void use2()
    {
      string s = "2012";
      int i = s.toint();
      response.write("使用扩展方法:" + i);
    }
 
    public static int strtoint(string s)
    {
      int id;
      int.tryparse(s, out id);//这里当转换失败时返回的id为0
      return id;
    }
  }
}

  以上是我对扩展方法理解及使用,如有不对或不足的地方请多多指正,谢谢啦。。

  这我第一次写文章算是排过版的,用好长时间呀,以前都只是看别人的文章,现在才知道写一篇好的文章真的不容易呀。

  努力学习,坚持自己的梦想。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网