要做多語系(Localization),我同樣借用了 XML 這項強大技術,於是資源本地化可以寫得非常直覺:
Resource.GetModule("Menu")["New"]
一行程式碼,就能取得對應語系的 Unicode 字串。它是怎麼運作的?先看設定檔。
<Resource>
<config module="Product">
<item key="Title">智睿方案框架管理系統</item>
<item key="SubTitle">——基於面向服務的多層架構</item>
<item key="Copyright">版權所有 ZIVSOFT 2000年-2008年</item>
<item key="Architect">滬ICP備07505171號</item>
</config>
<config module="Login">
<item key="Login">登陸</item>
<item key="Logout">退出</item>
<item key="UserName">用戶</item>
<item key="PassWord">密碼</item>
<item key="Title">登陸系統</item>
</config>
</Resource>
結構是兩層的:外層用 config 的 module 屬性區分「功能模組」,內層每個 item 用 key 對應一則文字。这样的文件可以準備多份,例如 ResourceCN.xml、ResourceEN.XML,換語言就是換檔案。
using System;
using System.Collections;
using System.Configuration;
using System.Xml;
using System.IO;
using System.Reflection;
using System.Diagnostics;
/*
* Created by Lihua at 2006-11-26
* https://www.zivsoft.com
*/
namespace Zivsoft.Localization
{
/// <summary>
/// Resource Files, Language Version Solution.
/// </summary>
public class Resource : IResource
{
/// <summary>
/// 已載入的 Resource 物件以 module 為索引被快取起來
/// </summary>
private static Hashtable _htStrRes;
/// <summary>
/// 單一 module 底下 key/value 的存放處
/// </summary>
private Hashtable _htData;
/// <summary>
/// 目前的 module 名稱
/// </summary>
private string _module;
private Resource(string module)
{
this._module = module;
this._htData = new Hashtable();
}
static Resource()
{
_htStrRes = new Hashtable();
}
/// <summary>
/// 取得目前語系識別碼
/// </summary>
public static string CultureId
{
get
{
var loader = new ResourceFileLoader();
return loader.GetCurrentLanguage();
}
}
/// <summary>
/// 依 Module ID 取得 Resource 物件
/// </summary>
public static Resource GetModule(string module)
{
if (module == null || module.Trim() == "")
{
throw new Exception("Resource-Instance: Module's value is null in resource files.");
}
// 命中快取就直接回傳,避免重複讀檔
if (_htStrRes.ContainsKey(module))
{
return _htStrRes[module] as Resource;
}
Resource strRes = new Resource(module);
strRes.LoadData();
_htStrRes.Add(module, strRes);
return strRes;
}
/// <summary>
/// 讀取 XML 資源檔,並把資料填進 hashtable
/// </summary>
private void LoadData()
{
this._htData.Clear();
string configName = null;
ResourceFileLoader loader = new ResourceFileLoader();
configName = loader.GetFullFilePath();
if (configName == string.Empty)
{
this._htData.Clear();
return;
}
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(configName);
XmlNode root = xmlDoc.DocumentElement;
foreach (XmlNode xNode in root.ChildNodes)
{
// 節點必須是 config
if (xNode.Name != "config")
{
continue;
}
// config 必須帶有 module 屬性
XmlAttribute attr = xNode.Attributes["module"];
if (null == attr)
{
continue;
}
// 找到目前要載入的 module
if (this._module == xNode.Attributes["module"].Value)
{
foreach (XmlNode item in xNode.ChildNodes)
{
attr = item.Attributes["key"];
if (null == attr || this._htData.ContainsKey(attr.Value))
{
continue;
}
this._htData.Add(attr.Value, item.InnerText);
}
break;
}
}
}
catch (Exception e)
{
Debug.WriteLine(e);
this._htData.Clear();
}
}
/// <summary>
/// 索引子:找不到 key 時回傳 [module][key] 方便排查
/// </summary>
public string this[string key]
{
get
{
string s = this._htData[key] as string;
string def = "[" + this._module + "][" + key + "]";
return s == null ? def : s;
}
}
public string GetKey(string key)
{
return this[key];
}
}
}
這份實作有三個值得沿用的想法。
第一是兩層快取。_htStrRes 是靜態的,以 module 名稱為索引快取整個 Resource 物件;_htData 則是每個物件內部 key/value 的對應表。第一次呼叫 GetModule("Login") 會讀檔解析,之後再呼叫就是純記憶體查表,幾乎零成本。
第二是取值的容錯設計。索引子找不到對應的 key 時,並不會丟出例外或回傳空字串,而是回傳 [module][key] 這樣的字樣。畫面上一旦出現這種字串,開發者立刻就知道是哪個模組少了哪個 key,不必翻 log。
第三是換語言只需換檔。因為所有邏輯都依賴 ResourceFileLoader 決定要載入哪一份 XML,新增語系時只要補上一份資源檔,程式碼完全不用動。這也是 XML 作為資源載體最大的好處:結構自明、擴充直觀、任何工具都能編輯。