C#基础知识之扩展方法

扩展方法需要满足的条件:

1、扩展方法必须定义在静态类里。

2、扩展方法必须是静态方法。

3、扩展方法的第一个参数以this修饰符为前缀。

4、扩展方法必须在使用它的类的扩展方法内,否则必须显示的using扩展方法所在的命名空间。

5、扩展方法只能被对象调用。

6、其他命名空间下的扩展方法优先级低于当前命名空间的扩展方法。

7、扩展方法完成之后,必须重新生成一次才会有有代码提示。

先写个简单的示例:

public static class DateTimeExtensions
{
    public static string ToString_yyyyMMddHHmmssffff(this DateTime dateTime)
    {
        return dateTime.ToString("yyyy-MM-dd HH:mm:ss.ffff");
    }
}
View Code

再来一个实例,在MVC3中,写个HtmlHelper的Include扩展方法,引入一个HTML页面的代码代码到当前页面。

namespace MVC_AjaxTest
{
    public static class Exten
    {
        public static string Include(this HtmlHelper htmlhelper,string path)  //扩展HtmlHelper类
        {
            string PhysicalPath = System.Web.HttpContext.Current.Server.MapPath(path);
            string str = File.ReadAllText(PhysicalPath);
            return str;  //返回读取到的字符串
        }
    }
}
View Code

然后在根目录新建一个text.htm代码如下:

<div style="background:red">你在他乡还好吗?</div>

  

视图代码:

@using MVC_AjaxTest
@Html.Raw(@Html.Include("/text.htm"));

要@Html.Raw()是为了防止输出的时候被Html编码了,这样就把源代码当成文字输出了而不解释HTML,浏览器显示代码如下:

 

原文地址:https://www.cnblogs.com/qtiger/p/11177071.html