深入Resource实现多语言支持的应用详解

所属分类: 软件编程 / C#教程 阅读数: 149
收藏 0 赞 0 分享

首先为假设有一个应用程序CAStudy,接着右键添加一个资源文件Resource1.resx

Resource1.resx里面如下:

image

Main函数如下:

static void Main()
{
    ResourceManager resourceManager = new ResourceManager(
        "CAStudy.Resource1",
        Assembly.GetExecutingAssembly());

    Console.WriteLine("String1 : " + resourceManager.GetString("String1"));
    Console.WriteLine("String1 : " + Resource1.String1);
    Console.ReadLine();
}

使用的ResourceManager构造函数如下:

[SecuritySafeCritical]
public ResourceManager(string baseName, Assembly assembly);

在应用程序编译的时候Resource1.resx就会被编译成Resource1的一个类。所以如果你不知道baseName是什么,也可以这样:

ResourceManager resourceManager = new ResourceManager(
                Resource1.ResourceManager.BaseName,
                Assembly.GetExecutingAssembly());

或者你查看IL代码,可以发现如下:

clip_image002 

运行结果如下:

clip_image002[5] 

假设我们要支持 英语-美国(en-US) 的人来访问的话:

clip_image002[7]

那么我们可以复制Resource1.resx ,从而生成Resource1.en-US.resx。

注意除了中间多出来了en-US之外,其他都相同,

当然,如果你需要支持中文-台湾,那么可以生成Resource1.zh-TW.resx.

Resource1.en-US.resx内容如下:

clip_image004 

可以看到,现在的是Hello。

使用的时候只需要修改

Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");

为什么修改 CurrentUICulture 就可以了呢?

// 摘要:
// 获取或设置资源管理器使用的当前区域性以便在运行时查找区域性特定的资源。
public CultureInfo CurrentUICulture { get; set; }

完整的Main函数如下:

static void Main()
{
  ResourceManager resourceManager = new ResourceManager(
    Resource1.ResourceManager.BaseName,
    Assembly.GetExecutingAssembly());

  Console.WriteLine("String1 :" + resourceManager.GetString("String1"));
  Console.WriteLine("String1 :" + Resource1.String1);

  Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
  Console.WriteLine("String1 :" + resourceManager.GetString("String1"));
  Console.WriteLine("String1 :" + Resource1.String1);

  Console.ReadLine();
}

运行结果如下:

clip_image002[9]

更多精彩内容其他人还在看

C# 大小写转换(金额)实例代码

C# 大小写转换(金额)实例代码,需要的朋友可以参考一下
收藏 0 赞 0 分享

C# WinForm中Panel实现用鼠标操作滚动条的实例方法

由于在WinForm中Panel不能直接响应鼠标的滚动事件,只好采用捕获窗体的滚动事件。
收藏 0 赞 0 分享

C#访问应用程序配置文件的方法

C#访问应用程序配置文件的方法,需要的朋友可以参考一下
收藏 0 赞 0 分享

C#读写文件的方法汇总

C#读写文件的方法汇总,需要的朋友可以参考一下
收藏 0 赞 0 分享

C#计算代码执行时间的方法

在一些测试工作时我们需要获得高精度的代码执行时间以比较其效率。
收藏 0 赞 0 分享

C# 动画窗体(AnimateWindow)的小例子

C# 动画窗体(AnimateWindow)的小例子,需要的朋友可以参考一下
收藏 0 赞 0 分享

C# zxing二维码写入的实例代码

C# zxing二维码写入的实例代码,需要的朋友可以参考一下
收藏 0 赞 0 分享

c#判断输入的是不是数字的小例子

c#判断输入的是不是数字的小例子,需要的朋友可以参考一下
收藏 0 赞 0 分享

c# 深拷贝与浅拷贝的区别分析及实例

浅拷贝(影子克隆):只复制对象的基本类型,对象类型,仍属于原来的引用. 深拷贝(深度克隆):不紧复制对象的基本类,同时也复制原对象中的对象.就是说完全是新对象产生的.
收藏 0 赞 0 分享

C#利用com操作excel释放进程的解决方法

最近利用Microsoft.Office.Interop.Excel.Application读取一个excel后,进程中一直存在excel,在网上找了一阵子,其中有几个解决方案
收藏 0 赞 0 分享
查看更多