C#中全局资源的最佳实践

7

当我们想要为所有用户(使用不同语言)制作应用程序时,我们需要一种全球技术。
在C#中,我们使用ResourceManager来实现:

using System;
using System.Reflection;
using System.Resources;

public class Example
{
   public static void Main()
   {
      // Retrieve the resource.
      ResourceManager rm = new ResourceManager("ExampleResources" , 
                               typeof(Example).Assembly);
      string greeting = rm.GetString("Greeting");

      Console.Write("Enter your name: ");
      string name = Console.ReadLine();
      Console.WriteLine("{0} {1}!", greeting, name);
   }
}
// The example produces output similar to the following:
//       Enter your name: John
//       Hello John!

这个程序集有两个或更多语言资源:
程序集
|--Assembly.en-us.resx
|--Assembly.zh-cn.resx

然后我们通过改变线程CultureInfo来改变资源以达到翻译的目的。

如果应用程序有很多dll(程序集)文件。
我想为应用程序拥有一个单一点(每种语言对应一个资源文件),
有没有好的解决方案来实现我的想法?

之前,我只是改变视图(例如Winform或UserControl)的 Language 来实现相应语言的不同UI。

2个回答

0

只需按照您描述的方式在C#中构建国际化即可。但是在构建过程的最后一步,您可以运行Fody.Costura

这将获取所有不同的dll并将它们打包到您的应用程序中,以便您只有一个包含所有内容的单个.exe文件。

好处是您可以按照预期使用C#国际化框架而无需任何黑客技巧,但仍然可以获得一个单独的exe文件,可以交付给您的客户。


0

我觉得C#的国际化框架非常不足,所以通常我会为资源制作一个程序集,并从其他项目中引用。我使用某些工具(如数据库、Excel、文本文件)生成资源文件,并将源数据和资源文件都纳入版本控制。

MyApp.sln
   ResourceProject.csproj   
     Resources.resx
     Resources.ru.resx
     Resources.de.resx
     Resource.cs
   Core.csproj
   UI.csproj

资源类可以加载所有不同的程序集。

 namespace MyApp.Resources
 {
    public static class Resource
    {
       private static ResourceManager manager;
       static Resource()
       {
          manager = new ResourceManager("MyApp.Resources", Assembly.GetAssembly(typeof(Resource)));
       }

       public static string GetString(string key, string culture)
       {
          return GetString(key, new CultureInfo(culture));
       }

       public static string GetString(string key, CultureInfo culture)
       {
          return manager.GetString(key, culture);
       }
    }
 }

这个简单的类可以以各种方式进行扩展。在调用程序集中,您可以拥有实用程序类,根据当前 UI 文化或线程文化情况下进行调用。

请注意,这完全绕过了任何内置的 WinForms 或 WPF i18N 方法。

对于 GUI,您可以创建一个实用程序,递归地翻译整个表单。查找本身可以/应该通过警告来扩展,以获取缺少的键、回退参数、前缀/命名空间(如果您有数千个键)等。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接