多語言實現方法有許多種,
1.利用VS2005自帶的資源文件去實現
2.重寫控件,給多語言賦值<myui:Lable key="language" runat=server />;
3.利用模板,內文格式如<input type="button" value="{search}" />
。。。
以下利用模板機制實現多語言:
原理是用正則式把所有的{XXX}讀取出來,然後替換,再寫回到頁面。
需要用到的命名空間:
using System.Text.RegularExpressions;
using System.Text;
using System.IO;
using System.Diagnostics;
具體代碼如下:
[copy to clipboard]
CODE:
protected override void Render(HtmlTextWriter writer)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Reset();
stopwatch.Start();
try
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);
base.Render(htw);
string content = sb.ToString();
//模板標簽{yes},{no},{search}
Regex re = new Regex(@"{\S+}", RegexOptions.Multiline);
MatchCollection mc = re.Matches(content);
//利用Hashtable來篩選所有的多語言標簽,然後做替換
Hashtable ht = new Hashtable();
//多語言的資源文件讀取到一個Hashtable裡,可以保存到緩存裡,
Hashtable ResurceHt = new Hashtable();
for (int i = 0; i < mc.Count; i++)
{
if (!ht.ContainsKey(mc.Value))
{
ht.Add(mc.Value, null);
//進行替換
content = content.Replace(mc.Value, (string)ResurceHt[mc.Value.TrimStart('{').TrimEnd('}')]);
}
}
ht.Clear();
//重新寫入頁面
writer.Write(content);
}
catch (Exception ex)
{
Response.Write(ex.ToString());
Response.End();
}
finally {
stopwatch.Stop();
Response.Write("runtime:" + stopwatch.ElapsedMilliseconds.ToString() + "ms");
}
}