【问题标题】:Collections in #c (ArrayList) in for loop or foreach with index#c (ArrayList) 中 for 循环或 foreach 中带有索引的集合
【发布时间】:2020-02-28 11:11:53
【问题描述】:

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

  1. 为什么不能用 Type 初始化 ArrayList

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

  1. 为什么我不能对 ArrayList 进行类型转换以访问 MyClass 的公共方法
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??
            }

【问题讨论】:

  • 使用List&lt;T&gt; 代替废弃 ArrayList
  • 您应该使用 List 而不是从 NET 历史开始就存在的 ArrayList 作为无类型集合
  • 如果您编写 ((MyClass)myAL[i]).getSomeValue();,您的第二个示例将起作用

标签: c# arraylist collections


【解决方案1】:
  1. 与 Java 不同,C# 中的 ArrayList 不是通用的。如果你想要一个类型参数,你应该使用来自System.Collections.Generic 命名空间的List&lt;T&gt;。 List&lt;T&gt; 实际上比 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&lt;T&gt;,则不需要强制转换。

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

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

【讨论】:

    【解决方案2】:

    foreach 使用 Enumerator 循环遍历集合,索引不是其中的一部分,而是使用 MoveNext。 MoveNext 强制循环移动到下一个对象

    假设列表是这样的

    List<MyClass> list = new List<MyClass>();
    

    然后在列表中获取枚举数

    var listEnumerator  =  list.GetEnumerator();
    

    然后使用for循环遍历listEnumerator

      for(var i = 0; listEnumerator.MoveNext() == true; i++ )
      {
          Console.WriteLine("Index: {0}  and value is: {1}", i, listEnumerator.Current);
      }
    

    输出

    Index: 0 and value is: value1 
    Index: 1 and value is: value2
    

    【讨论】:

      猜你喜欢
      • 2014-11-13
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      • 2018-01-14
      相关资源
      最近更新 更多