获取不同语言的语言名称

Obtain a language name in different languages

我有以下内容:

if (currentUICulture.Equals(CultureInfo.GetCultureInfo("fr-FR")))
    _EnglishLabel = "Anglais";
else
    _EnglishLabel = "English";

问我自己是否可以针对任意数量的当前文化优化此代码。

我可以尝试为当前 UI 文化获取它,如下所示:

_EnglishLabel = new CultureInfo("en-US").DisplayName;

但是如果我不通过 currentUICulture 给出英语,而是通过作为参数传递的任意区域性怎么办...

换句话说,如何获得

new CultureInfo("en-US").GetDisplayName(myArbitraryCulture);

PS.

.NET 框架代码

////////////////////////////////////////////////////////////////////////
//
//  DisplayName
//
//  Returns the full name of the CultureInfo in the localized language.
//  For example, if the localized language of the runtime is Spanish and the CultureInfo is
//  US English, "Ingles (Estados Unidos)" will be returned.
//
////////////////////////////////////////////////////////////////////////
public virtual String DisplayName
{
    [System.Security.SecuritySafeCritical]  // auto-generated
    get
    {
        Contract.Ensures(Contract.Result<String>() != null);
        Contract.Assert(m_name != null, "[CultureInfo.DisplayName]Always expect m_name to be set");

        return m_cultureData.SLOCALIZEDDISPLAYNAME;
    }
}

////////////////////////////////////////////////////////////////////////
//
//  GetNativeName
//
//  Returns the full name of the CultureInfo in the native language.
//  For example, if the CultureInfo is US English, "English
//  (United States)" will be returned.
//
////////////////////////////////////////////////////////////////////////
public virtual String NativeName {
    [System.Security.SecuritySafeCritical]  // auto-generated
    get {
        Contract.Ensures(Contract.Result<String>() != null);
        return (this.m_cultureData.SNATIVEDISPLAYNAME);
    }
}

可以检索已安装 框架语言的翻译。工作原理没有记录,但可以在参考源中看到内部实现(例如 CultureData)。 对于已安装文化以外的目标文化,将返回英语回退。

在此基础上,我们可以使用以下内容(同样,仅适用于已安装的框架语言):

public static string GetDisplayName(this CultureInfo culture, CultureInfo locale)
{
    var rm = new ResourceManager("mscorlib", typeof(object).Assembly);
    var resourceKey = $"Globalization.ci_{culture.Name}";
    return rm.GetString(resourceKey, locale);
}

例如安装了瑞典语和英语:

var culture = CultureInfo.GetCultureInfo("en");
var swedishName = culture.GetDisplayName(CultureInfo.GetCultureInfo("sv")); // Engelska
var englishName = culture.GetDisplayName(CultureInfo.GetCultureInfo("en")); // English
var germanName = culture.GetDisplayName(CultureInfo.GetCultureInfo("de")); // English <- German not installed

为了涵盖所有语言(或任意语言集合),我建议使用非本地方法,因为内置方法并不能真正支持您的用例。

干杯!