CommaDelimitedStringCollection Класс

Определение

Представляет коллекцию строковых элементов, разделенных запятой. Этот класс не наследуется.

public ref class CommaDelimitedStringCollection sealed : System::Collections::Specialized::StringCollection
public sealed class CommaDelimitedStringCollection : System.Collections.Specialized.StringCollection
type CommaDelimitedStringCollection = class
    inherit StringCollection
Public NotInheritable Class CommaDelimitedStringCollection
Inherits StringCollection
Наследование
CommaDelimitedStringCollection

Примеры

В следующем примере кода показано, как использовать CommaDelimitedStringCollection тип .

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Configuration;
using System.Collections.Specialized;

namespace Samples.AspNet.Config
{
  class CommaDelimitedStrCollection
  {
    static void Main(string[] args)
    {
      // Display title and info.
      Console.WriteLine("ASP.NET Configuration Info");
      Console.WriteLine("Type: CommaDelimitedStringCollection");
      Console.WriteLine();

      // Set the path of the config file.
      string configPath = "/aspnet";

      // Get the Web application configuration object.
      Configuration config = 
        WebConfigurationManager.OpenWebConfiguration(configPath);

      // Get the section related object.
      AuthorizationSection configSection =
        (AuthorizationSection)config.GetSection("system.web/authorization");

      // Get the authorization rule collection.
      AuthorizationRuleCollection authorizationRuleCollection = 
        configSection.Rules;

      // Create a CommaDelimitedStringCollection object.
      CommaDelimitedStringCollection myStrCollection =
        new CommaDelimitedStringCollection();

      for (int i = 0; i < authorizationRuleCollection.Count; i++)
      {
        if (authorizationRuleCollection.Get(i).Action.ToString().ToLower() 
          == "allow")
        {
          // Add values to the CommaDelimitedStringCollection object.
          myStrCollection.AddRange(
            authorizationRuleCollection.Get(i).Users.ToString().Split(
            ",".ToCharArray()));
        }
      }

      Console.WriteLine("Allowed Users: {0}",
        myStrCollection.ToString());

      // Count the elements in the collection.
      Console.WriteLine("Allowed User Count: {0}", 
        myStrCollection.Count);

      // Call the Contains method.
      Console.WriteLine("Contains 'userName1': {0}",
        myStrCollection.Contains("userName1"));

      // Determine the index of an element
      // in the collection.
      Console.WriteLine("IndexOf 'userName0': {0}",
        myStrCollection.IndexOf("userName0"));

      // Call IsModified.
      Console.WriteLine("IsModified: {0}",
        myStrCollection.IsModified);

      // Call IsReadyOnly.
      Console.WriteLine("IsReadOnly: {0}",
        myStrCollection.IsReadOnly);

      Console.WriteLine();
      Console.WriteLine("Add a user name to the collection.");
      // Insert a new element in the collection.
      myStrCollection.Insert(myStrCollection.Count, "userNameX");

      Console.WriteLine("Collection Value: {0}",
        myStrCollection.ToString());

      Console.WriteLine();
      Console.WriteLine("Remove a user name from the collection.");
      // Remove an element of the collection.
      myStrCollection.Remove("userNameX");

      Console.WriteLine("Collection Value: {0}",
        myStrCollection.ToString());

      // Display and wait
      Console.ReadLine();
    }
  }
}
Imports System.Collections.Generic
Imports System.Text
Imports System.Configuration
Imports System.Collections
Imports System.Web
Imports System.Web.Configuration
Imports System.Collections.Specialized

Namespace Samples.AspNet.Config
  Class CommaDelimitedStrCollection
    Shared Sub Main(ByVal args() As String)
      ' Display title and info.
      Console.WriteLine("ASP.NET Configuration Info")
      Console.WriteLine("Type: CommaDelimitedStringCollection")
      Console.WriteLine()

      ' Set the path of the config file.
      Dim configPath As String = "/aspnet"

      ' Get the Web application configuration object.
      Dim config As Configuration = _
      WebConfigurationManager.OpenWebConfiguration(configPath)

      ' Get the section related object.
      Dim configSection As AuthorizationSection = _
      CType(config.GetSection("system.web/authorization"), AuthorizationSection)

      ' Get the authorization rule collection.
      Dim authorizationRuleCollection As AuthorizationRuleCollection = _
      configSection.Rules()

      ' Create a CommaDelimitedStringCollection object.
      Dim myStrCollection As CommaDelimitedStringCollection = _
        New CommaDelimitedStringCollection()

      Dim i As Integer
      For i = 0 To authorizationRuleCollection.Count - 1 Step i + 1
        If authorizationRuleCollection.Get(i).Action.ToString().ToLower() _
          = "allow" Then
          ' Add values to the CommaDelimitedStringCollection object.
          myStrCollection.AddRange( _
            authorizationRuleCollection.Get(i).Users.ToString().Split( _
            ",".ToCharArray()))
        End If
      Next

      Console.WriteLine("Allowed Users: {0}", _
        myStrCollection.ToString())

      ' Count the elements in the collection.
      Console.WriteLine("Allowed User Count: {0}", _
        myStrCollection.Count)

      ' Call the Contains method.
      Console.WriteLine("Contains 'userName1': {0}", _
        myStrCollection.Contains("userName1"))

      ' Determine the index of an element
      ' in the collection.
      Console.WriteLine("IndexOf 'userName0': {0}", _
        myStrCollection.IndexOf("userName0"))

      ' Call IsModified.
      Console.WriteLine("IsModified: {0}", _
        myStrCollection.IsModified)

      ' Call IsReadyOnly.
      Console.WriteLine("IsReadOnly: {0}", _
        myStrCollection.IsReadOnly)

      Console.WriteLine()
      Console.WriteLine("Add a user name to the collection.")
      ' Insert a new element in the collection.
      myStrCollection.Insert(myStrCollection.Count, "userNameX")

      Console.WriteLine("Collection Value: {0}", _
        myStrCollection.ToString())

      Console.WriteLine()
      Console.WriteLine("Remove a user name from the collection.")
      ' Remove an element of the collection.
      myStrCollection.Remove("userNameX")

      Console.WriteLine("Collection Value: {0}", _
        myStrCollection.ToString())

      ' Display and wait
      Console.ReadLine()
    End Sub
  End Class
End Namespace

Комментарии

Этот класс представляет коллекцию строк, сериализованную в виде списка строковых элементов с разделителями-запятыми.

Конструкторы

CommaDelimitedStringCollection()

Создает новый экземпляр класса CommaDelimitedStringCollection.

Свойства

Count

Получает число строк, содержащихся в коллекции StringCollection.

(Унаследовано от StringCollection)
IsModified

Возвращает значение, указывающее, была ли коллекция изменена.

IsReadOnly

Возвращает значение, указывающее, является ли объект коллекции доступным только для чтения.

IsSynchronized

Возвращает значение, показывающее, является ли доступ к коллекции StringCollection синхронизированным (потокобезопасным).

(Унаследовано от StringCollection)
Item[Int32]

Возвращает или задает строковый элемент в коллекции по указанному индексу.

SyncRoot

Получает объект, с помощью которого можно синхронизировать доступ к коллекции StringCollection.

(Унаследовано от StringCollection)

Методы

Add(String)

Добавляет строку в коллекцию, разделенную запятыми.

AddRange(String[])

Добавляет все строки из строкового массива в коллекцию.

Clear()

Очищает коллекцию.

Clone()

Создает копию коллекции.

Contains(String)

Определяет, входит ли указанная строка в коллекцию StringCollection.

(Унаследовано от StringCollection)
CopyTo(String[], Int32)

Копирует значения всей коллекции StringCollection в одномерный массив строк, начиная с указанного индекса целевого массива.

(Унаследовано от StringCollection)
Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetEnumerator()

Возвращает объект StringEnumerator, осуществляющий перебор StringCollection.

(Унаследовано от StringCollection)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
IndexOf(String)

Осуществляет поиск указанной строки и возвращает отсчитываемый от нуля индекс ее первого вхождения в коллекцию StringCollection.

(Унаследовано от StringCollection)
Insert(Int32, String)

Добавляет строковый элемент в коллекцию по указанному индексу.

MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
Remove(String)

Удаляет строковый элемент из коллекции.

RemoveAt(Int32)

Удаляет строку по указанному индексу в StringCollection.

(Унаследовано от StringCollection)
SetReadOnly()

Устанавливает коллекцию в режим только для чтения.

ToString()

Возвращает строковое представление объекта.

Явные реализации интерфейса

ICollection.CopyTo(Array, Int32)

Копирует целый массив StringCollection в совместимый одномерный массив Array, начиная с заданного индекса целевого массива.

(Унаследовано от StringCollection)
IEnumerable.GetEnumerator()

Возвращает объект IEnumerator, осуществляющий перебор StringCollection.

(Унаследовано от StringCollection)
IList.Add(Object)

Добавляет объект в конец коллекции StringCollection.

(Унаследовано от StringCollection)
IList.Contains(Object)

Определяет, входит ли элемент в коллекцию StringCollection.

(Унаследовано от StringCollection)
IList.IndexOf(Object)

Осуществляет поиск указанного объекта Object и возвращает отсчитываемый от нуля индекс первого вхождения в коллекцию StringCollection.

(Унаследовано от StringCollection)
IList.Insert(Int32, Object)

Вставляет элемент в коллекцию StringCollection по указанному индексу.

(Унаследовано от StringCollection)
IList.IsFixedSize

Получает значение, показывающее, имеет ли объект StringCollection фиксированный размер.

(Унаследовано от StringCollection)
IList.IsReadOnly

Получает значение, показывающее, является ли объект StringCollection доступным только для чтения.

(Унаследовано от StringCollection)
IList.Item[Int32]

Возвращает или задает элемент по указанному индексу.

(Унаследовано от StringCollection)
IList.Remove(Object)

Удаляет первое вхождение указанного объекта из коллекции StringCollection.

(Унаследовано от StringCollection)

Методы расширения

Cast<TResult>(IEnumerable)

Приводит элементы объекта IEnumerable к заданному типу.

OfType<TResult>(IEnumerable)

Выполняет фильтрацию элементов объекта IEnumerable по заданному типу.

AsParallel(IEnumerable)

Позволяет осуществлять параллельный запрос.

AsQueryable(IEnumerable)

Преобразовывает коллекцию IEnumerable в объект IQueryable.

Применяется к

См. также раздел