國際化的軟體往往需要多種語言資源,如何在C#的WinForm中做到呢?且看以下分解:
1 工程添加資源檔
資源檔命名方式 [資源檔主題名].[語言地區.].resx
例如資源檔主題名為: "Resource1" 。我們準備了 中 英 日 三個語言版本的資源檔,則對應的語言地區分別是 "zh-CN"、"en"、"ja"。
所以我們添加了三個資源檔: Resource1.zh-CN.resx 、Resource1.en.resx、 Resource1.ja.resx
2 添加命名空間(反射、資源、進程、國際化)
using System.Reflection;
using System.Resources;
using System.Threading;
using System.Globalization;
3 擷取資源檔管理器
ResourceManager rm = new ResourceManager("winGetMsgFromResource.Resource1", Assembly.GetExecutingAssembly());
資源檔名的構成為 [項目命名空間].[資源檔主題名]
4 擷取當前進程的語言地區
CultureInfo ci = Thread.CurrentThread.CurrentCulture;
5 從資源檔中按項目名擷取值
假定MsgId是資源檔中的項目名
rm.GetString(MsgId, ci);
6 前台國際化環境的選擇(改變當前程式進程中的地區資訊的方式達到改變)
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("zh-CN");
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-us");
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("ja-JP");
執行個體:一個簡單的資源檔訪問類
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Resources;
using System.Threading;
using System.Globalization;
namespace winGetMsgFromResource
{
class clsMsg
{
public static string getMsg(string MsgId)
{
ResourceManager rm = new ResourceManager("winGetMsgFromResource.Resource1", Assembly.GetExecutingAssembly());
CultureInfo ci = Thread.CurrentThread.CurrentCulture;
return rm.GetString(MsgId, ci);
}
public static string getMsg1()
{
string strOut = string.Empty;
CultureInfo ci = Thread.CurrentThread.CurrentCulture;
switch (ci.ToString())
{
case "zh-CN":
strOut = "當前 文化地區 為 中文";
break;
case "en-US":
strOut = "Current Culture is ENGLISH";
break;
case "ja-JP":
strOut = "現在の言葉は 日本語です";
break;
default:
strOut = "others";
break;
}
return strOut;
}
}
}
樣本工程
/Files/heekui/winGetMsgFromResource.rar