我有一个小型测试应用程序,其中有 2 个资源文件(Resources.resx
和 Resources.de-DE.resx
),它们具有完全相同的字符串名称,但其中一个具有字符串转换为德语。
对于我的表单,我将 Localize 属性设置为 ture。
在我的应用程序中,我得到的字符串如下:
this.Text = Properties.Resources.frmCaption;
在我的发布文件夹中,我得到一个 de-DE
文件夹,其中包含一个名为 International_test.resources.dll
的 dll。
我尝试将其分发到设置为德语的机器,并且所有拉动的字符串仍然是英语。
我尝试将 International_test.resources.dll
保留在 de-DE
文件夹中,或者直接放入我的 apps
目录中。
我做错了什么或者我需要做什么才能使用德语资源文件?
最佳答案
幸运的是,我使用 hello world 原型(prototype)项目来测试构建管道中的一大堆东西。
假设您已正确设置资源文件,下面的一些示例代码可能会有所帮助。为了简洁起见,删除了代码文档。
public class HelloWorld
{
public CultureInfo CultureInfo { get; private set; }
public HelloWorld()
{
CultureInfo = CultureInfo.CurrentCulture;
}
public HelloWorld(string culture)
{
CultureInfo = CultureInfo.GetCultureInfo(culture);
}
public string SayHelloWorld()
{
return Resources.ResourceManager.GetString("HelloWorld", CultureInfo);
}
}
[TestFixture]
public class HelloWorldFixture
{
HelloWorld helloWorld;
[Test]
public void Ctor_SetsCultureInfo_ToCurrentCultureForParameterlessCtor()
{
helloWorld = new HelloWorld();
Assert.AreEqual(helloWorld.CultureInfo, CultureInfo.CurrentCulture,
"Expected CultureInfo to be set as CurrentCulture");
}
[Test]
public void Ctor_SetsCultureInfo_ToAustralianCulture()
{
helloWorld = new HelloWorld("en-AU");
Assert.AreEqual(helloWorld.CultureInfo.Name, "en-AU",
"Expected CultureInfo to be set to Australian culture");
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void Ctor_ThrowsException_InvalidCultureName()
{
helloWorld = new HelloWorld("Bogus");
}
[Test]
public void SayHelloWorld_ReturnsFallbackResource_OnUndefinedResource()
{
helloWorld = new HelloWorld("en-JM");
string result = helloWorld.SayHelloWorld();
Assert.AreEqual("Hello, World.", result, "Expected fallback resource string to be used");
}
[Test]
public void SayHelloWorld_ReturnsAustralianResource_OnAustralianResource()
{
helloWorld = new HelloWorld("en-AU");
string result = helloWorld.SayHelloWorld();
Assert.AreEqual("G'Day, World.", result, "Expected australian resource string to be used");
}
}
此项目有 Resources.resx 文件,其中包含 HelloWorld 字符串键项和 “Hello, World” 值,以及相应的 Resources.en-AU.resx 包含 HelloWorld 字符串键项和 “G'Day,World” 值,以及其他内容,例如 zh-CH (我只气垫船装满晒鳝.:) 测试非英文字符的显示,因为它显示在关联的 hello world web 项目中。
最后,添加一些日志记录以显示正在使用的区域性(为了简洁起见,我将其从本示例中取出),并检查编译器输出以确保调用 AL.exe 来链接您的资源程序集(听起来没问题)不过)。
关于c# - 国际化 HelloWorld 程序 .NET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1129053/