多語言實現方案眾多,常見的有:VS 資源檔、重寫控件賦值、以及模板替換法。本文介紹一種基於模板與正則替換的輕量級方案。
頁面中以 {key} 格式標記多語言佔位符,後端在 Render 階段攔截輸出 HTML,用正則提取所有佔位符,從資源表(可快取)查找對應語言文本並替換,最後寫回響應流。
using System.Text.RegularExpressions;
using System.Text;
using System.IO;
using System.Diagnostics;
protected override void Render(HtmlTextWriter writer)
{
Stopwatch sw = new Stopwatch();
sw.Start();
try
{
StringBuilder sb = new StringBuilder();
StringWriter swriter = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(swriter);
base.Render(htw);
string content = sb.ToString();
// 匹配 {xxx} 格式標籤
Regex re = new Regex(@"{\S+}", RegexOptions.Multiline);
MatchCollection mc = re.Matches(content);
// 用 Hashtable 去重並替換
Hashtable ht = new Hashtable();
Hashtable resourceHt = GetResourceTable(); // 從快取/資源檔讀取
foreach (Match m in mc)
{
string key = m.Value;
if (!ht.ContainsKey(key))
{
ht.Add(key, null);
string dictKey = key.Trim('{', '}');
if (resourceHt.ContainsKey(dictKey))
{
content = content.Replace(key, (string)resourceHt[dictKey]);
}
}
}
ht.Clear();
writer.Write(content);
}
catch (Exception ex)
{
Response.Write(ex.ToString());
Response.End();
}
finally
{
sw.Stop();
Response.Write("runtime:" + sw.ElapsedMilliseconds + "ms");
}
}
此法適合中小型專案快速加入多語言支援,大型系統建議採用官方資源檔方案。