上一篇說到:為了可擴充與友善大夥,我定義了一個抽象類,先實作了三個正則用于截取标題,說明,和關鍵字。
抽象類代碼簡潔如下:

public abstract class replacetextlistbase
{
/// <summary>
/// 将被傳回的替換文本集合清單
/// </summary>
public dictionary<string, string> replacetextlist = new dictionary<string, string>();
/// 擷取目前請求頁面的url資訊
public uri pageurl { get { return httpcontext.current.request.url; } }
/// 擷取html的title的正則
public string titleregex { get { return "<title.*>.*</title>"; } }
public string titleformat(string titletext)
{
return "<title>" + titletext + "</title>";
}
/// 擷取html的description的正則
public string descriptionregex { get { return "<meta[^<>]+name=[\"\']description[^<>]*[/]>"; } }
public string descriptionformat(string descriptiontext)
return "<meta id=\"description\" name=\"description\" content=\"" + descriptiontext + "\" />";
/// 擷取html的keyword的正則
public string keywordregex { get { return "<meta[^<>]+name=[\"\']keywords[^<>]*[/]>"; } }
public string keywordformat(string keywordtext)
return "<meta id=\"keywords\" name=\"keywords\" content=\"" + keywordtext + "\" />";
/// 複寫此方法,調用replacetextlist.add()方法後,return replacetextlist;
/// <returns></returns>
public virtual dictionary<string, string> getreplacetextlist()
return replacetextlist;
}

抽象類後,留下一個虛方法getreplacetextlist(), 這是重點
現在看一下我的示例中的子類的實作,繼承自抽象類,複寫虛方法:

public class replacetextlist:replacetextlistbase
{
public override system.collections.generic.dictionary<string, string> getreplacetextlist()
replacetextlist.add(titleregex,titleformat("titleregex"));
replacetextlist.add(descriptionregex,descriptionformat("descriptionttest"));
replacetextlist.add(keywordregex,keywordformat("keywordadfdfdf"));
}

代碼解析:
例子中的子類實作很簡單,就複寫了一個虛方法,最終頁面的輸出标題為:titleregex。其它兩個同理。
如果要替換其它或過濾檔案,隻要寫多幾個add方法把要替換的文字給替換掉就行了,具體也可以結合下資料庫或其它檔案操作
另外說明:
例子上,直接就定死了标題輸出為:titleregex,這裡可以結合自己的需要,替換成任意字元串。
提示:抽象類裡還留下了pageur吧,可以根據url查出title和description和keyword來實作自己的擴充。
另外給出一些我早期實作的思路:
建資料庫表,對url主機頭進行分類管理,自己定義替換字元等,最後查詢與替換。
版權聲明:本文原創發表于部落格園,作者為路過秋天,原文連結:http://www.cnblogs.com/cyq1162/archive/2009/03/04/1403321.html