C#CultureInfo.GetCultures返回一个空列表

时间:2011-08-03 07:58:02

标签: c# cultureinfo

我无法使用GetCultures,我可以告诉它返回一个空白列表。

private void AddressChooser_Load(object sender, EventArgs e)
    {
        MessageBox.Show("Form load event successfully triggered") //Debug message - This appears at runtime
        foreach (string country in GetCountryList())
        {
            MessageBox.Show(country); //Debug message - This does not appear at runtime!!
            countryBox.Items.Clear();
            countryBox.Items.Add(country);
        }
    }

    public static List<string> GetCountryList()
    {
        MessageBox.Show("Function has been triggered successfully"); //Debug message - This appears at runtime
        List<string> cultureList = new List<string>();
        CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures);
        foreach (CultureInfo culture in cultures)
        {
            RegionInfo region = new RegionInfo(culture.LCID);
            if (!(cultureList.Contains(region.EnglishName)))
                cultureList.Add(region.EnglishName);
            MessageBox.Show(region.EnglishName); //Debug message - This does not appear at runtime!
        }
        return cultureList;
    }

我觉得奇怪的是,这不起作用,因为它只是一个复制和粘贴的片段。 请帮忙! 感谢

3 个答案:

答案 0 :(得分:5)

你必须在某个地方的地板下扫一个例外。

您的代码失败,因为CultureTypes.AllCultures & ~CultureTypes.NeutralCultures不起作用。您的列表包含中性文化和new RegionInfo()投掷。

摘录:

var c1 = CultureTypes.AllCultures & ~CultureTypes.NeutralCultures;
Console.WriteLine(c1);

生成SpecificCultures, InstalledWin32Cultures,我想这些Win32文化包含中性文化。

简单的解决方案是CultureInfo.GetCultures(CultureTypes.SpecificCultures);

但要解决的主要问题是你的异常处理和调试技术。

答案 1 :(得分:2)

首先,调试&gt;&gt;异常并将CLR运行时执行命令设置为Thrown是个好主意。其次,我认为这段代码可以是你想要的:

        static void Main()
        {
            List<string> cultureList = new List<string>();
            CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures);
            foreach (CultureInfo culture in cultures)
            {   
                try
                {
                    RegionInfo region = new RegionInfo(culture.Name);
                    if (!(cultureList.Contains(region.EnglishName)))
                        cultureList.Add(region.EnglishName);
                    Console.WriteLine(region.EnglishName); 
                }
                catch (ArgumentException e)
                {
                    Console.WriteLine(String.Format("For{0} a specific culture name is required.", culture.Name));
                }                  
            }
        }

答案 2 :(得分:-1)

在此使用按位代替 CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures);