栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

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

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

Resource1.resx里面如下:

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代码,可以发现如下:

 

运行结果如下:

 

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

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

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

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

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

 

可以看到,现在的是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();
}

运行结果如下:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/127318.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号