为什么" foreach"循环返回键,而#34;索引器"返回NameValueCollection中的值

时间:2015-12-19 16:52:58

标签: c# .net for-loop foreach namevaluecollection

我有一个NameValueCollection,它包含几个项目。当我尝试从该集合中检索值时,它会从集合中返回

NameValueCollection col= new NameValueCollection();
    col.Add("Item1", "Foo");
    col.Add("Item2", "Bar");
    col.Add("Item3", "Pooh");
    col.Add("Item4", "Car");
    foreach (string val in col) 
    {
       if (val == "Item3") //val contains the Key from the collection
          { break; }
    }

另一方面,如果我尝试在for循环中从索引器中检索值,那么它会从集合中返回 Value

for (int i = 0; i < col.Count; i++) 
{
    string val = col[i];
    if (val == "Pooh") //val contains the 'Value' from the NameValueCollection
    {
       break;
    }
}

为什么这些不同类型的循环有不同类型的结果?

2 个答案:

答案 0 :(得分:1)

如果我们查看C#源代码,我们可以看到为什么会发生这种情况:

<强> Indexer

/// <devdoc>
/// <para>Represents the entry at the specified index of the <see cref='System.Collections.Specialized.NameValueCollection'/>.</para>
/// </devdoc>
public String this[int index] {
    get 
    {
        return Get(index);
    }
}

索引器,您在循环中使用i变量访问的内容,返回该索引处的值。

<强> Enumerator

/// <devdoc>
/// <para>Returns an enumerator that can iterate through the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/>.</para>
/// </devdoc>
public virtual IEnumerator GetEnumerator() {
    return new NameObjectKeysEnumerator(this);
}

枚举器,使用foreach语句时获得的内容,为您提供NameValueCollection的键列表。

答案 1 :(得分:1)

NameValueCollection

  

表示关联的String键和String值的集合   可以使用密钥或索引访问。

ForEach访问String键
col [val]将通过键

访问该值

在第二个中,您通过索引

访问该值