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
- 如果您需要直接访问索引,则循环。
关于c# - #c (ArrayList) 中的集合在 for 循环或带有索引的 foreach 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58671354/