深入Resource實現(xiàn)多語言支持的應(yīng)用詳解
首先為假設(shè)有一個應(yīng)用程序CAStudy,接著右鍵添加一個資源文件Resource1.resx。
Resource1.resx里面如下:
Main函數(shù)如下:
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構(gòu)造函數(shù)如下:
[SecuritySafeCritical]
public ResourceManager(string baseName, Assembly assembly);
在應(yīng)用程序編譯的時候Resource1.resx就會被編譯成Resource1的一個類。所以如果你不知道baseName是什么,也可以這樣:
ResourceManager resourceManager = new ResourceManager(
Resource1.ResourceManager.BaseName,
Assembly.GetExecutingAssembly());
或者你查看IL代碼,可以發(fā)現(xiàn)如下:
運行結(jié)果如下:
假設(shè)我們要支持 英語-美國(en-US) 的人來訪問的話:
那么我們可以復(fù)制Resource1.resx ,從而生成Resource1.en-US.resx。
注意除了中間多出來了en-US之外,其他都相同,
當然,如果你需要支持中文-臺灣,那么可以生成Resource1.zh-TW.resx.
Resource1.en-US.resx內(nèi)容如下:
可以看到,現(xiàn)在的是Hello。
使用的時候只需要修改
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
為什么修改 CurrentUICulture 就可以了呢?
// 摘要: // 獲取或設(shè)置資源管理器使用的當前區(qū)域性以便在運行時查找區(qū)域性特定的資源。 public CultureInfo CurrentUICulture { get; set; }
完整的Main函數(shù)如下:
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(); }
運行結(jié)果如下:
相關(guān)文章
C#中如何在Excel工作表創(chuàng)建混合型圖表實例
本篇文章主要介紹了C#中如何在Excel工作表創(chuàng)建混合型圖表實例,具有一定的參考價值,有需要的可以了解一下。2016-11-11C# char[]與string byte[]與string之間的轉(zhuǎn)換詳解
在本篇文章里小編給大家分享的是關(guān)于C# char[]與string byte[]與string之間的轉(zhuǎn)換的知識點內(nèi)容,需要的朋友們參考下2019-11-11C# 獲取數(shù)據(jù)庫中所有表名、列名的示例代碼
這篇文章主要介紹了C# 獲取數(shù)據(jù)庫中所有表名、列名,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06C#利用ASP.NET?Core開發(fā)學(xué)生管理系統(tǒng)詳解
隨著技術(shù)的進步,跨平臺開發(fā)已經(jīng)成為了標配,在此大背景下,ASP.NET?Core也應(yīng)運而生。本文主要利用ASP.NET?Core開發(fā)一個學(xué)生管理系統(tǒng),感興趣的可以學(xué)習一下2022-01-01C#使用yield關(guān)鍵字讓自定義集合實現(xiàn)foreach遍歷的方法
這篇文章主要介紹了C#使用yield關(guān)鍵字讓自定義集合實現(xiàn)foreach遍歷的方法,需要的朋友可以參考下2014-08-08