我目前正在将数据存储到数组中。该程序从文本文件中获取信息,然后使用产品名称格式化结果。问题是,如果在文本的起始行中找不到数字(int),则文件会中断。具体在productID = Convert.ToInt16(storeData[0]);。如果文本文件中的第一个字符不是整数,如何避免破坏程序?

信息在文本文件中的外观:ProductID,Month和Sales

1 5 20.00



string[] productName = new string[100];
                string arrayLine;
                int[] count = new int[100];
                int productID = 0;
                double individualSales = 0;
                double[] totalSales = new double[100];
                double[] totalAverage = new double[100];

                productName[1] = "Cookies";
                productName[2] = "Cake";
                productName[3] = "Bread";
                productName[4] = "Soda";
                productName[5] = "Soup";
                productName[99] = "Other";

                while ((arrayLine = infile.ReadLine()) != null)
                {


                    string[] storeData = arrayLine.Split(' ');

                    productID = Convert.ToInt16(storeData[0]);
                    individualSales = Convert.ToDouble(storeData[2]);

                    if (stateName[productID] != null)
                    {
                        count[productID] += 1;
                        totalSales[stateID] += individualSales;
                    }
                    else
                    {
                        count[99] += 1;
                        totalSales[99] += individualSales;
                    }


                }
                infile.Close();

最佳答案

if (!Int16.TryParse(storeData[0], out productID))
   continue;//or do something else


Int16.TryParse

如Gromer所述,我宁愿使用int.TryParse(实际上是Int32.TryParse)...

关于c# - 将数据存储到数组中并检查其是否为有效整数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12533879/

10-10 18:46