📌  相关文章
📜  C#|获取或设置StringCollection中指定索引处的元素

📅  最后修改于: 2021-05-29 20:45:39             🧑  作者: Mango

StringCollection.Item [Int32]属性用于获取或设置指定索引处的元素。

句法:

public string this[int index] { get; set; }

在这里, index是要获取或设置的条目的从零开始的索引。

返回值:返回指定索引处String类型的元素。

异常:如果索引小于零或索引等于或大于Count,则此属性引发ArgumentOutOfRangeException

下面的程序说明了上面讨论的属性的用法:

范例1:

// C# code to get or set the element at
// the specified index in StringCollection
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // creating a StringCollection named myCol
        StringCollection myCol = new StringCollection();
  
        // Adding elements in StringCollection
        myCol.Add("A");
        myCol.Add("B");
        myCol.Add("C");
        myCol.Add("D");
        myCol.Add("E");
  
        // Displaying objects in myCol
        foreach(Object obj in myCol)
        {
            Console.WriteLine(obj);
        }
  
        Console.WriteLine("\nAfter Item[int32] Property: \n");
  
        // setting the value at index 2
        myCol[2] = "Z";
  
        // Displaying the elements
        // in the StringCollection
        foreach(Object obj1 in myCol)
        {
            Console.WriteLine(obj1);
        }
    }
}

输出:

A
B
C
D
E

After Item[int32] Property: 

A
B
Z
D
E

范例2:

// C# code to get or set the element at
// the specified index in StringCollection
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // creating a StringCollection named myCol
        StringCollection myCol = new StringCollection();
  
        // Adding elements in StringCollection
        myCol.Add("Geeks");
        myCol.Add("GFG");
        myCol.Add("DS");
        myCol.Add("Class");
        myCol.Add("Noida");
  
        // Displaying objects in myCol
        foreach(Object obj in myCol)
        {
            Console.WriteLine(obj);
        }
  
        Console.WriteLine("\nAfter Item[int32] Property: \n");
  
        // setting the value at index 8
        // this will give error as index
        // is greater than count
        myCol[8] = "C#";
  
        // Displaying the elements
        // in the StringCollection
        foreach(Object obj1 in myCol)
        {
            Console.WriteLine(obj1);
        }
    }
}

运行时错误:

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.specialized.stringcollection.item?view=netframework-4.7.2