We all know that an important method in the arraylist class is add (). This method is used to add elements to the set. It has an object-type parameter, this method can be used to add any type of items to the set. Because the elements in the arraylist dynamic array can be diversified, when you use the foreach statement to traverse the arraylist array, it may cause potential problems to the program.
The Code is as follows:
class Program { //遍历arraylist出现的问题分析 static void Main(string[] args) { ArrayList arr = getArrayList(); foreach (int item in arr) { Console.WriteLine(item.ToString()); } Console.ReadLine(); } static ArrayList getArrayList()//声明getArrayList()的方法,返回arraylist的实例。 { ArrayList arr = new ArrayList(); //动态数组的元素都为整型。 arr.Add(1); arr.Add(2); arr.Add(3); return arr; } }
Well, there is no problem. What if so?
class Program { //遍历arraylist出现的问题分析 static void Main(string[] args) { ArrayList arr = getArrayList(); foreach (int item in arr) { Console.WriteLine(item.ToString()); } Console.ReadLine(); } static ArrayList getArrayList()//声明getArrayList()的方法,返回arraylist的实例。 { ArrayList arr = new ArrayList(); //动态数组的元素都为整型。 arr.Add(1); arr.Add(2); arr.Add(3); //添加浮点型的元素 arr.Add(2f); //添加日期类型的元素 arr.Add(DateTime.Today); //添加字符型元素 arr.Add("hello"); return arr; } }
Well, the problem is as follows:
If the specified conversion is invalid, select it and quickly monitor it. We found that:
When the value of item is 3, that is, when the fourth element is int, and the value of item is 3, the corresponding element type is float. to convert it to int, the conversion will inevitably fail.
After thinking for a long time, we found that we can filter out the arraylist before traversing it. Therefore, we have a solution. As follows:
class Program { //遍历arraylist出现的问题分析 static void Main(string[] args) { ArrayList arr = getArrayList(); int[]intArray=arr.OfType<int>().ToArray<int>(); foreach (int item in intArray) { Console.WriteLine(item.ToString()); } Console.ReadLine(); } static ArrayList getArrayList()//声明getArrayList()的方法,返回arraylist的实例。 { ArrayList arr = new ArrayList(); //动态数组的元素都为整型。 arr.Add(1); arr.Add(2); arr.Add(3); //添加浮点型的元素 arr.Add(2f); //添加日期类型的元素 arr.Add(DateTime.Today); //添加字符型元素 arr.Add("hello"); return arr; } }
After debugging, this can avoid this problem. The effect is as follows:
Possible problems when traversing the arraylist Array