c#中英文切换实例
1.創建兩個資源文件
Resource.en-US.resx? ? ??Resource.zh-CN.resx? ? 注意中間部分每種語言文件名固定,后綴名是.resx,首部分是自定義的名字
2.創建讀寫工具類
上面兩個資源文件都是在Utility項目集中
當另一個含有UI的項目調用次Utility里的資源時需要引用此項目,然后編譯后在UI的項目debug中會自動生成嵌入的文件如:
debug\en-US\Utility.resources.dll? ?和debug\zh-CN\Utility.resources.dll?
注意:
ResourceManager rm = new ResourceManager("Utility.Resource", Assembly.GetExecutingAssembly());的調用就要以命名空間+資源文件首部名的形式。
?
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Threading;
namespace WindowsFormsApplication1
{
? ? public class Utility
? ? {
? ? ? ? /// <summary>
? ? ? ? /// Set current culture by name
? ? ? ? /// </summary>
? ? ? ? /// <param name="name">name</param>
? ? ? ? public static void SetCurrentCulture(string name)
? ? ? ? {
? ? ? ? ? ? if (string.IsNullOrEmpty(name))
? ? ? ? ? ? {
? ? ? ? ? ? ? ? name = "CN";
? ? ? ? ? ? }
? ? ? ? ? ? Thread.CurrentThread.CurrentCulture = new CultureInfo(name);
? ? ? ? }
? ? ? ? /// <summary>
? ? ? ? /// Get string by id
? ? ? ? /// </summary>
? ? ? ? /// <param name="id">id</param>
? ? ? ? /// <returns>current language string</returns>
? ? ? ? public static string GetString(string id)
? ? ? ? {
? ? ? ? ? ? string strCurLanguage = "";
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? ResourceManager rm = new ResourceManager("Utility.Resource", Assembly.GetExecutingAssembly());
? ? ? ? ? ? ? ? CultureInfo ci = Thread.CurrentThread.CurrentCulture;
? ? ? ? ? ? ? ? strCurLanguage = rm.GetString(id, ci);
? ? ? ? ? ? }
? ? ? ? ? ? catch(Exception ee)
? ? ? ? ? ? {
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? strCurLanguage = "No id:" + id + ", please add.";
? ? ? ? ? ? }
? ? ? ? ? ? return strCurLanguage;
? ? ? ? }
? ? }
}
3.界面
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
? ? public partial class Form1 : Form
? ? {
? ? ? ? public Form1()
? ? ? ? {
? ? ? ? ? ? InitializeComponent();
? ? ? ? }
? ? ? ? private void button1_Click(object sender, EventArgs e)
? ? ? ? {
? ? ? ? ? ? Utility.SetCurrentCulture("zh-CN");
? ? ? ? ? ? this.textBox1.Text = Utility.GetString("a1");
? ? ? ? }
? ? ? ? private void button2_Click(object sender, EventArgs e)
? ? ? ? {
? ? ? ? ? ? Utility.SetCurrentCulture("en-US");
? ? ? ? ? ? this.textBox1.Text = Utility.GetString("a1");
? ? ? ? }
? ? }
}
?
總結
- 上一篇: 解决 VUE: 本地运行和服务器上运行样
- 下一篇: 如何在 IDEA 启动多个 Spring