Skip to main content
 首页 » 编程设计

c#之#c (ArrayList) 中的集合在 for 循环或带有索引的 foreach 中

2024年02月25日30Renyi-Fan

C# 对我来说是新手,我正在尝试遍历一个集合,在这种情况下,我尝试了我的一个类的 ArrayList,我经常在 Java 中使用它。目标是循环比较ArrayList,得到当前位置的索引。

  1. 为什么不能用类型启动 ArrayList

ArrayList<MyClass> myAL = new ArrayList<MyClass>();

  1. 为什么我不能对 ArrayList 进行类型转换以访问 MyClass 的公共(public)方法
ArrayList myAL = new ArrayList(); 
            for (int i=0; i<myAL.Count; i++) 
            { 
                (MyClass)myAL[i].getSomeValue(); 
            } 
  1. 唯一有效的循环是 foreach 循环,但我不知道如何访问索引。
foreach (MyClass mc in myAL) 
            { 
                mc.getSomeValue(); 
                //index?? 
            } 

请您参考如下方法:

  1. 与 Java 不同,ArrayList在 C# 中不是通用的。如果你想要一个类型参数,你应该使用 List<T>来自 System.Collections.Generic命名空间。 List<T>实际上比 ArrayList 更受欢迎- 后者仍然存在,主要是为了向后兼容。
List<MyClass> myAL = new List<MyClass>(); 
  1. 你需要一对额外的括号:
ArrayList myAL = new ArrayList(); 
for (int i = 0; i < myAL.Count; i++) 
{ 
    ((MyClass)myAL[i]).getSomeValue(); 
} 

但是如果你使用 List<T> 就不需要转换了.

  1. 您不能直接访问 foreach 中的索引循环,但您可以定义一个变量来保存它。
int index = 0; 
foreach (MyClass mc in myAL) 
{ 
    // do stuff with the list item and an index 
    index++; 
} 

但我建议使用简单的 for - 如果您需要直接访问索引,则循环。