代码改变世界

ASP.NET中的扩展方法

2011-05-19 18:19  爱慕司黛尔  阅读(268)  评论(0)    收藏  举报

以前没有怎么用过,真是OUT

基本语法是 this type parm

public static string ToCustomString(this string str, string str_1){
    return "test_" + str_1;
}

说明:

以上定义了一个String 类的扩展方法,使用方法很简单,任何类型为 String 的变量都可以直接调用此方法。举个例子

public string ReturnTest(){
    string s = "s";
    return s.ToCustomString("XXX");//这里像调用 ToString()方法一样直接使用即可。
}

必须注意的是,扩展方法必须保证是 static 类型的,并且其方法所在的类也必须是static 类型的。

完整的定义如下

public static class CustomClass{
    public static string ToCustomString(this string str, string str_1){
        return "test_" + str_1;
    }
}

//使用扩展方法
public class UseClass{
    public string UseCustomFun(){
        string s="s";
        return s.ToCustomString("xxx");
    }
}

同时附上ASP.NET MVC PAGER 分面的HTMLHELPER

public static string Pager(this HtmlHelper helper, int currentPage, int currentPageSize, int totalRecords, string urlPrefix)
    {
        StringBuilder sb1 = new StringBuilder();

        int seed = currentPage % currentPageSize == 0 ? currentPage : currentPage - (currentPage % currentPageSize);

        if(currentPage > 0)
            sb1.AppendLine(String.Format("<a href=\"{0}/{1}\">Previous</a>", urlPrefix, currentPage));

        if(currentPage - currentPageSize >= 0)
            sb1.AppendLine(String.Format("<a href=\"{0}/{1}\">...</a>", urlPrefix, (currentPage - currentPageSize) + 1));

        for (int i = seed; i < Math.Round((totalRecords / 10) + 0.5) && i < seed + currentPageSize; i++)
        {
            sb1.AppendLine(String.Format("<a href=\"{0}/{1}\">{1}</a>", urlPrefix, i + 1));
        }

        if (currentPage + currentPageSize <= (Math.Round((totalRecords / 10) + 0.5) - 1))
            sb1.AppendLine(String.Format("<a href=\"{0}/{1}\">...</a>", urlPrefix, (currentPage + currentPageSize) + 1));

        if (currentPage < (Math.Round((totalRecords / 10) + 0.5) - 1))
            sb1.AppendLine(String.Format("<a href=\"{0}/{1}\">Next</a>", urlPrefix, currentPage + 2));

        return sb1.ToString();
    }