C#扩展方法

来源:互联网 发布:淘宝怎么上传商品 编辑:程序博客网 时间:2024/05/11 10:50

第一步:

先创建一个解决方案

                

一个类库Common用来存放扩展方法类的。 一个用来测试的winform

                Linq项目引用Common。

第二步

编写ExpandFunc扩展方法类,里面只写了俩个方法。

扩展方法规定类必须是一个静态类,ExpandFunc是一个静态类,里面包含的所有方法都必须是静态方法。

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

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

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

IsRange的静态方法,他接收一个自身参数this,类型为DateTime,后面跟着要传进来的参数


 

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Common{    /// <summary>    /// 扩展方法必须为静态类    /// </summary>    public static class  ExpandFunc    {        /// <summary>        /// 把字符串转为int        /// </summary>        /// <param name="text"></param>        /// <returns></returns>        public static int ToInt(this String text)        {            int result;            int.TryParse(text,out result);            return result;        }        /// <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;        }    }}

下面开始进行测试

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using Common;namespace Linq{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {            String num = "123";            MessageBox.Show((num.ToInt()+123)+"");//246            DateTime dt1 = new DateTime(2011,2,2);            DateTime dt2 = new DateTime(2015, 2, 2);            DateTime dt3 = new DateTime(2010, 2, 2);            int res = dt1.IsRange(dt3, dt2);            MessageBox.Show(res.ToString());//0  dt1在dt2和dt3范围里,                    }        }}

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

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