C# 对我来说是新手,我正在尝试遍历一个集合,在这种情况下,我尝试了我的一个类的 ArrayList,我经常在 Java 中使用它。目标是循环比较ArrayList,得到当前位置的索引。
- 为什么不能用类型启动 ArrayList
ArrayList<MyClass> myAL = new ArrayList<MyClass>();
- 为什么我不能对 ArrayList 进行类型转换以访问 MyClass 的公共(public)方法
ArrayList myAL = new ArrayList();
for (int i=0; i<myAL.Count; i++)
{
(MyClass)myAL[i].getSomeValue();
}
- 唯一有效的循环是 foreach 循环,但我不知道如何访问索引。
foreach (MyClass mc in myAL)
{
mc.getSomeValue();
//index??
}
请您参考如下方法:
- 与 Java 不同,
ArrayList在 C# 中不是通用的。如果你想要一个类型参数,你应该使用List<T>来自System.Collections.Generic命名空间。List<T>实际上比ArrayList更受欢迎- 后者仍然存在,主要是为了向后兼容。
List<MyClass> myAL = new List<MyClass>();
- 你需要一对额外的括号:
ArrayList myAL = new ArrayList();
for (int i = 0; i < myAL.Count; i++)
{
((MyClass)myAL[i]).getSomeValue();
}
但是如果你使用 List<T> 就不需要转换了.
- 您不能直接访问
foreach中的索引循环,但您可以定义一个变量来保存它。
int index = 0;
foreach (MyClass mc in myAL)
{
// do stuff with the list item and an index
index++;
}
但我建议使用简单的 for - 如果您需要直接访问索引,则循环。
