1 using System; 2 using System.Collections; 3 4 namespace C_9_4 5 { 6 class Program 7 { 8 private static void test_1(ArrayList b) 9 { 10 int i; 11 if (b.IndexOf("SB") != -1) 12 { 13 Console.WriteLine("找到了目标值,下标为{0} 并输出数据检查是否正确", b.IndexOf("SB")); 14 15 for (i = 0; i < b.Count; i++) 16 { 17 Console.WriteLine("{0}", b[i]); 18 } 19 } 20 else 21 { 22 Console.WriteLine("没有找到对应值"); 23 } 24 25 } 26 static void Main(string[] args) 27 { 28 //ArrayList.IndexOf 29 //索引方法 30 //格式 ArrayList.IndexOf(Object,Int32_1,Int32_2); 31 //在ArrayList集合里面寻找Object元素,并且只返回第一个对应元素的下标, 32 //Int32_1 起始元素的下标,Int32_2 搜索元素的范围 33 //简单来讲就是,Int32_1确定从第几个开始查,Int32_2决定往后查几个数据 34 35 ArrayList a = new ArrayList() { 1, 2, 3, 4, 5, 6, 6, 6, 6 }; 36 Console.WriteLine("{0}", a.IndexOf(6, 2, 5));//5 37 //这里的返还值是5,虽然我们是从2开始索引的,但是并不会改变结果的下标 38 //并且他只识别到了第一个6,后面的6都没有计算。 39 40 Console.WriteLine("{0}", a.IndexOf("SB", 2, 5));//-1 41 //当ArrayList.IndexOf索引不到对象的时候,就会返回-1 42 43 //还有另外两种简单的办法 44 //1.ArrayList.IndexOf(Object) 45 //直接在ArrayList中全局索引来找object 46 Console.WriteLine("{0}", a.IndexOf(6));//5 47 48 //2.ArrayList.IndexOf(Object,Int32_1); 49 //在原有的基础上添加了Int32_1用来选择索引数据的起始项 50 Console.WriteLine("{0}", a.IndexOf(6, 4));//5 51 52 //注意:这里Int32_1的索引位置也是下标,也就是说从前面往后面数的时候,要从0开始 53 // 而后面的int32则是直接的加上数。 54 55 56 //ArrayList.Insert() 57 //讲某个元素直接插入在指定位置 58 //格式:ArrayList.Insert(Int32,Object) 59 //Int32就是0的索引位置 60 ArrayList b = new ArrayList() { 5, 4, 2, 44, 8, 9 }; 61 //然后为了验证是否插入成功,我们调用te函数进行检测 62 test_1(b);//对象引用非静态的静态,属性,或方法Program.test_1是必须的 63 //我也不知这是什么意思,大概对应非静态的还有别的操作吧,于是我把test_1改成了静态的 64 //返回的结果是没有找到 65 66 //b.Insert(10,"SB"); 67 //test_1(b ); 68 //这样是会报错的,因为我们设的b是没有10位的长度的,但是这个方法是怎么添加的呢》 69 70 b.Insert(0,"SB"); 71 test_1(b); 72 73 b = new ArrayList() { 5, 4, 2, 44, 8, 9 }; 74 b.Insert(5, "SB"); 75 test_1(b); 76 77 b = new ArrayList() { 5, 4, 2, 44, 8, 9 }; 78 b.Insert(6, "SB"); 79 test_1(b); 80 81 /* 82 b = new ArrayList() { 5, 4, 2, 44, 8, 9 }; 83 b.Insert(7, "SB"); 84 test_1(b); 85 86 */ 87 88 //通过上述的测试,我们发现,ArrayList.Insert的插入方式 89 //直接插入到Int32的位置,对于其他的数据,前面不动,后面全部后移 90 //并且可以插入到ArrayList.Count有效长度+1位的位置 91 //再往后不能插入,因为没有开设堆空间了 92 93 } 94 95 } 96 97 98 99 100 101 }