17

我有一个字符串,我需要验证它是否是国家代码。文化是德国人。有什么方法可以调用来获取德国文化中的国家/地区代码列表,而无需自己输入所有 274(?)代码?

谢谢,泰加。

4

6 回答 6

17

当您说“国家代码”时,我假设您的意思是ISO 3166中的两个字母代码。然后您可以使用 RegionInfo 构造函数来检查您的字符串是否是正确的代码。

string countryCode = "de";
try {
    RegionInfo info = new RegionInfo(countryCode);
}
catch (ArgumentException argEx)
{
    // The code was not a valid country code
}

正如您在问题中所述,您还可以检查它是否是德语的有效国家代码。然后你只需传入一个特定的文化名称和国家代码。

string language = "de";
string countryCode = "de";
try {
    RegionInfo info = new RegionInfo(string.Format("{0}-{1}", language, countryCode));
}
catch (ArgumentException argEx)
{
    // The code was not a valid country code for the specified language
}
于 2009-08-24T20:44:54.247 回答
12

接受的答案是ArgumentException对构造函数抛出的错误使用。您并没有真正使用RegionInfoArgumentException实例,这使得代码的目的非常不清楚。

相反,获取所有特定文化的列表,然后搜索这些文化的区域以在您的 ISO 3166 alpha-2 代码中找到匹配项:

bool IsCountryCodeValid(string countryCode)
{
    return CultureInfo
        .GetCultures(CultureTypes.SpecificCultures)
            .Select(culture => new RegionInfo(culture.LCID))
                .Any(region => region.TwoLetterISORegionName == countryCode);
}

或者具体来说,对于您的问题:

bool IsValidGermanCountryCode(string countryCode)
{
    return CultureInfo
        .GetCultures(CultureTypes.SpecificCultures)
            .Where(culture => culture.TwoLetterISOLanguageName == "de")
                .Select(culture => new RegionInfo(culture.LCID))
                    .Any(region => region.TwoLetterISORegionName == countryCode);
}
于 2015-01-28T22:53:26.680 回答
4

如果您只需要国家/地区,您可以使用 RegionInfo 类:http: //msdn.microsoft.com/en-us/library/system.globalization.regioninfo.aspx

于 2009-08-24T18:55:39.443 回答
1

http://cldr.unicode.org/ - 通用标准多语言数据库包括国家列表和其他可本地化的数据。

于 2011-02-08T09:57:53.370 回答
1

使用时要小心RegionInfo检查有效的 ISO 代码。如果您提供的代码有效并且它是受支持的区域,它将返回一个区域,但它不会对所有有效的 ISO 3166 代码执行此操作。

有关更完整的解释,请参见此处:https ://social.msdn.microsoft.com/Forums/en-US/c9a8bc14-d571-4702-91a6-1b80da239009/question-of-regioninfo-and-region-cy

RegionInfo在欧洲可以正常工作,但是有几个非洲国家没有使用这种方法进行验证(例如乌干达)。

于 2016-01-08T11:10:18.597 回答
1

你可以使用我的 nuget 包Nager.Country。每个国家/地区都有很多附加信息。更多信息请访问Github 项目

PM> install-package Nager.Country
var countryCode = "de";
ICountryProvider countryProvider = new CountryProvider();
var countryInfo = countryProvider.GetCountry(countryCode);
if (countryInfo != null)
{
    //country exists
}
于 2020-12-29T20:18:31.130 回答