How to use localization in C#

后端 未结 9 2458
栀梦
栀梦 2020-11-22 02:59

I just can\'t seem to get localization to work.

I have a class library. Now I want to create resx files in there, and return some values based on the threa

9条回答
  •  孤独总比滥情好
    2020-11-22 03:07

    A fix and elaboration of @Fredrik Mörk answer.

    • Add a strings.resx Resource file to your project (or a different filename)
    • Set Access Modifier to Public (in the opened strings.resx file tab)
    • Add a string resouce in the resx file: (example: name Hello, value Hello)
    • Save the resource file

    Visual Studio auto-generates a respective strings class, which is actually placed in strings.Designer.cs. The class is in the same namespace that you would expect a newly created .cs file to be placed in.

    This code always prints Hello, because this is the default resource and no language-specific resources are available:

    Console.WriteLine(strings.Hello);
    

    Now add a new language-specific resource:

    • Add strings.fr.resx (for French)
    • Add a string with the same name as previously, but different value: (name Hello, value Salut)

    The following code prints Salut:

    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("fr-FR");
    Console.WriteLine(strings.Hello);
    

    What resource is used depends on Thread.CurrentThread.CurrentUICulture. It is set depending on Windows UI language setting, or can be set manually like in this example. Learn more about this here.

    You can add country-specific resources like strings.fr-FR.resx or strings.fr-CA.resx.

    The string to be used is determined in this priority order:

    • From country-specific resource like strings.fr-CA.resx
    • From language-specific resource like strings.fr.resx
    • From default strings.resx

    Note that language-specific resources generate satellite assemblies.

    Also learn how CurrentCulture differs from CurrentUICulture here.

提交回复
热议问题