在来看扩展方法前,先来出一个小问题。
写一个方法,能在给定的字符串两边加上"☆"。很简单吧。
public static string AddStar(string s)
{
return "☆" + s + "☆";
}
现在由于特殊原因,需要连续调用三次这个方法,亲肿么办呢?
![偷笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/titter.gif)
static void Main(string[] args)
{
string str = "secret";
str = MyStringHelper.AddStar(MyStringHelper.AddStar(MyStringHelper.AddStar(str)));
}
现在觉得如何,有没有感觉已经麻烦了?那么问题又来了。
我很希望我自己写的方法也能像 string.Trim().SubString().Replace()这样来调用,因为这样很爽。
那么具体该怎么办呢,这里就要用到叫做扩展方法的东西。
先来看实现【只需三步】
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 扩展方法
{
//1:首先将帮助方法的类变为static类
public static class MyStringHelper
{
//2:方法也是静态的 //3:第一个参数前加 this
public static string AddStar(this string s)
{
return "☆" + s + "☆";
}
}
}
其中第三步是 为哪个类进行扩展的意思
实现的时候简洁明了
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 扩展方法
{
class Program
{
static void Main(string[] args)
{
string str = "secret";
//str = MyStringHelper.AddStar(MyStringHelper.AddStar(MyStringHelper.AddStar(str)));
str = str.AddStar().AddStar().AddStar();
}
}
}
扩展方法:
扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。对于用 C# 和 Visual Basic 编写的客户端代码,调用扩展方法与调用在类型中实际定义的方法之间没有明显的差异。(引自csdn)
扩展方法的应用可以让程序简洁明了。下面是我项目中用到的实例
【在MVC3中扩展MvcHtmlString类型,创建分页标签】
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
namespace System.Web.Mvc
{
//1:在帮助类上标明为static类
public static class MyHtmlHelperExt
{
//2:方法为static方法
//3:为HtmlHelper类进行扩展,所以第一个参数为this HtmlHelper
public static MvcHtmlString GetPageBar(this HtmlHelper htmlHelper,int pageIndex,int pageSize,int totle)
{
var redirectTo = htmlHelper.ViewContext.HttpContext.Request.Url.AbsolutePath;
//确定每一页多少条数据
pageSize = pageSize <= 0 ? 15 : pageSize;
//根据总记录数和每一页的条数算出 多少页pageCount
int pageCount = (int)Math.Ceiling((double)totle/pageSize);
//得到strat end 的值
pageIndex = pageIndex<1?1:pageIndex;
int start = pageIndex - 4;
if (start < 1) start = 1;
int end = start + 8;
if (end > pageCount) end = pageCount;
//循环输出页码<a></a>标签,绑定样式“class=page_nav”
var outPut = new StringBuilder();
outPut.Append("<div class='page_nav'>");
outPut.AppendFormat("<span>{0}条数据 共{1}页 </span>",totle,pageCount);
if (pageIndex > 1)
{
//如果当前页大于1,那么就有上一页按钮
outPut.AppendFormat("<a href='{0}?pageIndex={1}&pageSize={2}'><上一页</a>", redirectTo, pageIndex - 1, pageSize);
}
for (int i = start; i <= end;i++ )
{
if (i == pageIndex)
{
//如果循环的变量i等于当前页,就不拼接a标签,而是拼接strong标签
outPut.AppendFormat("<strong>{0}</strong>",i.ToString());
}
else
{
outPut.AppendFormat("<a href='{0}?pageIndex={1}&pageSize={2}'>{1}</a>", redirectTo, i, pageSize);
}
}
if (pageIndex < pageCount)
{
//如果当前页小于总页数,那么就有下一页按钮
outPut.AppendFormat("<a href='{0}?pageIndex={1}&pageSize={2}'>下一页></a>", redirectTo, pageIndex + 1, pageSize);
}
outPut.Append("</div>");
return MvcHtmlString.Create(outPut.ToString());
}
}
}
这样@Html就能直接点出GetPageBar方法。
当然也可以扩展string类,写邮箱校验,密码校验,身份证校验等方法。