C# 中的 StringCollection 类

csharpserver side programmingprogramming更新于 2025/9/20 7:52:17

StringCollection 类表示字符串集合。以下是 StringCollection 类的属性 −

Sr.no属性 &说明
1Count
获取 OrderedDictionary 集合中包含的键/值对的数量。
2IsReadOnly
获取一个值,指示 StringCollection 是否为只读。
3IsSynchronized
获取一个值,指示对 StringCollection 的访问是否同步(线程安全)。
4Item[Int32]
获取或设置指定位置的元素索引。
5SyncRoot
获取可用于同步对 StringCollection 的访问的对象。

以下是 StringCollection 类的方法 −

Sr.no方法 &说明
1Add(String)
将字符串添加到 StringCollection 的末尾。
2AddRange(String[])
将字符串数组的元素复制到 StringCollection 的末尾。
3Clear()
从 StringCollection 中删除所有字符串。
4Contains(String)
确定指定的字符串是否在StringCollection。
5CopyTo(String[],Int32)
将整个 StringCollection 值复制到一个一维字符串数组中,从目标数组的指定索引处开始。
6Equals(Object)
判断指定对象是否等于当前对象。 (继承自 Object)
7GetEnumerator()
返回一个遍历 StringCollection 的 StringEnumerator。

现在来看一些示例

要检查两个 StringCollection 对象是否相等,代码如下 −

示例

using System;
using System.Collections.Specialized;
public class Demo {
   public static void Main() {
      StringCollection strCol1 = new StringCollection();
      strCol1.Add("Accessories");
      strCol1.Add("Books");
      strCol1.Add("Electronics");
      Console.WriteLine("StringCollection1 elements...");
      foreach (string res in strCol1) {
         Console.WriteLine(res);
      }
      StringCollection strCol2 = new StringCollection();
      strCol2.Add("Accessories");
      strCol2.Add("Books");
      strCol2.Add("Electronics");
      Console.WriteLine("StringCollection2 elements...");
      foreach (string res in strCol1) {
         Console.WriteLine(res);
      }
      Console.WriteLine("Both the String Collections are equal? = "+strCol1.Equals(strCol2));
   }
}

输出

这将产生以下输出 −

StringCollection1 elements...
Accessories
Books
Electronics
StringCollection2 elements...
Accessories
Books
Electronics
Both the String Collections are equal? = False

检查指定的字符串是否在StringCollection中,代码如下 −

示例

using System;
using System.Collections.Specialized;
public class Demo {
   public static void Main() {
      StringCollection stringCol = new StringCollection();
      String[] arr = new String[] { "100", "200", "300", "400", "500" };
      Console.WriteLine("Array elements...");
      foreach (string res in arr) {
         Console.WriteLine(res);
      }
      stringCol.AddRange(arr);
      Console.WriteLine("Does the specified string is in the StringCollection? = "+stringCol.Contains("800"));
   }
}

输出

这将产生以下输出 −

Array elements...
100
200
300
400
500
Does the specified string is in the StringCollection? = False

相关文章