程式裡常有錯誤碼、狀態標識或枚舉值,為了方便,這些通常不會直接用中文,而是採用 FileError 這類代號或數字。問題是,這些資訊最終往往要呈現給使用者,而使用者真正需要的是好懂的中文描述。以往的做法不是把轉換規則硬寫進程式,就是直接把代號丟給使用者——前者缺乏擴充性,後者則讓人一頭霧水。本文示範用 XML 設定檔保存提示資訊,再透過一個物件把機器內碼翻譯成人話。
以下用 C# 實作一個靜態翻譯類 Translation,它會從 XML 設定檔讀取對照表,並監聽檔案變動自動重載:
public static class Translation
{
private static FileSystemWatcher watcher;
private static XmlDocument content;
private static string configFile;
private static object locker = new object();
// 載入指定設定檔,並註冊變更事件
public static void Configure(string configFile)
{
LoadFile(configFile);
if (watcher != null) watcher.Dispose();
watcher = new FileSystemWatcher(
Path.GetDirectoryName(configFile), Path.GetFileName(configFile));
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
}
// 檔案變動時重新載入
private static void watcher_Changed(object sender, FileSystemEventArgs e)
{
LoadFile(configFile);
}
private static void LoadFile(string configFile)
{
lock (locker)
{
XmlDocument doc = new XmlDocument();
doc.Load(configFile);
content = doc;
Translation.configFile = configFile;
}
}
}
對於帶有 Flags 特性的枚舉,可以逐一比對位元並以分隔符號串接各段說明:
public static string GetEnumDescription(Enum enumValue, string sparator)
{
Type type = enumValue.GetType();
object[] attrs = type.GetCustomAttributes(typeof(FlagsAttribute), false);
if (attrs.Length > 0)
{
StringBuilder builder = new StringBuilder();
foreach (Enum enu in Enum.GetValues(type))
{
if ((Convert.ToUInt64(enumValue) & Convert.ToUInt64(enu)) == Convert.ToUInt64(enu))
{
builder.Append(GetEnumDes(type, enu.ToString()));
builder.Append(sparator);
}
}
return builder.ToString();
}
else
return GetEnumDes(type, enumValue.ToString());
}
而一般值的翻譯,則是用 XPath 到設定檔中查對照表:
public static string GetValueDescription(string group, object obj)
{
if (obj == null) return null;
string xquery = "/translation/description[@group='" + group + "']/add[@key='" + obj.ToString() + "']/@value";
XmlNode node = content.SelectSingleNode(xquery);
return node == null ? obj.ToString() : node.Value;
}
這種做法最大的好處是:提示文字與程式邏輯徹底分離,要調整或增補翻譯內容只需改 XML,甚至能在程式運行時透過 FileSystemWatcher 自動生效,不必重新編譯。