Поделиться через


CharEnumerator Класс

Определение

Поддерживает итерацию по объекту String и чтение отдельных символов. Этот класс не может быть унаследован.

public ref class CharEnumerator sealed : ICloneable, System::Collections::Generic::IEnumerator<char>
public ref class CharEnumerator sealed : ICloneable, System::Collections::IEnumerator
public sealed class CharEnumerator : ICloneable, System.Collections.Generic.IEnumerator<char>
[System.Serializable]
public sealed class CharEnumerator : ICloneable, System.Collections.IEnumerator
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class CharEnumerator : ICloneable, System.Collections.Generic.IEnumerator<char>
type CharEnumerator = class
    interface IEnumerator<char>
    interface IEnumerator
    interface IDisposable
    interface ICloneable
[<System.Serializable>]
type CharEnumerator = class
    interface IEnumerator
    interface ICloneable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type CharEnumerator = class
    interface ICloneable
    interface IEnumerator<char>
    interface IDisposable
    interface IEnumerator
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type CharEnumerator = class
    interface ICloneable
    interface IEnumerator<char>
    interface IEnumerator
    interface IDisposable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type CharEnumerator = class
    interface IEnumerator
    interface ICloneable
    interface IEnumerator<char>
    interface IDisposable
Public NotInheritable Class CharEnumerator
Implements ICloneable, IEnumerator(Of Char)
Public NotInheritable Class CharEnumerator
Implements ICloneable, IEnumerator
Наследование
CharEnumerator
Атрибуты
Реализации

Примеры

В следующем примере класс используется CharEnumerator для перечисления отдельных символов в строке. Он создает экземпляр объекта String.GetEnumerator путем вызова метода, перемещается CharEnumerator от одного символа к следующему путем вызова MoveNext метода и отображает текущий символ, извлекая значение Current свойства.

string title = "A Tale of Two Cities";
CharEnumerator chEnum = title.GetEnumerator();
int ctr = 1;
string outputLine1 = null;
string outputLine2 = null;
string outputLine3 = null;

while (chEnum.MoveNext())
{
   outputLine1 += ctr < 10 || ctr % 10 != 0 ? "  " : (ctr / 10) + " ";
   outputLine2 += (ctr % 10) + " ";
   outputLine3 += chEnum.Current + " ";
   ctr++;
}

Console.WriteLine("The length of the string is {0} characters:",
                  title.Length);
Console.WriteLine(outputLine1);
Console.WriteLine(outputLine2);
Console.WriteLine(outputLine3);
// The example displays the following output to the console:
//       The length of the string is 20 characters:
//                         1                   2
//       1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
//       A   T a l e   o f   T w o   C i t i e s
let title = "A Tale of Two Cities"
let chEnum = title.GetEnumerator()

printfn $"The length of the string is {title.Length} characters:"

let mutable outputLine1 = ""
let mutable outputLine2 = ""
let mutable outputLine3 = ""
let mutable i = 1

while chEnum.MoveNext() do
    outputLine1 <- outputLine1 + if i < 10 || i % 10 <> 0 then "  " else $"{i / 10} "
    outputLine2 <- outputLine2 + $"{i % 10} ";
    outputLine3 <- outputLine3 + $"{chEnum.Current} "
    i <- i + 1

printfn "%s" outputLine1
printfn "%s" outputLine2
printfn "%s" outputLine3

// The example displays the following output to the console:
//       The length of the string is 20 characters:
//                         1                   2
//       1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
//       A   T a l e   o f   T w o   C i t i e s
Dim title As String = "A Tale of Two Cities"
Dim chEnum As CharEnumerator = title.GetEnumerator()
Dim ctr As Integer = 1
Dim outputLine1, outputLine2, outputLine3 As String 

Do While chEnum.MoveNext()
   outputLine1 += CStr(iif(ctr < 10 Or ctr Mod 10 <> 0, "  ", CStr(ctr \ 10) + " ")) 
   outputLine2 += (ctr Mod 10)& " "
   outputLine3 += chEnum.Current & " "
   ctr += 1
Loop

Console.WriteLine("The length of the string is {0} characters:", _
                  title.Length)
Console.WriteLine(outputLine1)
Console.WriteLine(outputLine2)    
Console.WriteLine(outputLine3)
' The example displays the following output to the console:      
'       The length of the string is 20 characters:
'                         1                   2
'       1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
'       A   T a l e   o f   T w o   C i t i e s

Обратите внимание, что та же операция может выполняться несколько более интуитивно с помощью foreach (в C#) или For Each (в Visual Basic), как показано в следующем примере.

string title = "A Tale of Two Cities";
int ctr = 1;
string outputLine1 = null;
string outputLine2 = null;
string outputLine3 = null;

foreach (char ch in title)
{
   outputLine1 += ctr < 10 || ctr % 10 != 0 ? "  " : (ctr / 10) + " ";
   outputLine2 += (ctr % 10) + " ";
   outputLine3 += ch + " ";
   ctr++;
}

Console.WriteLine("The length of the string is {0} characters:",
                  title.Length);
Console.WriteLine(outputLine1);
Console.WriteLine(outputLine2);
Console.WriteLine(outputLine3);
// The example displays the following output to the console:
//       The length of the string is 20 characters:
//                         1                   2
//       1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
//       A   T a l e   o f   T w o   C i t i e s
let title = "A Tale of Two Cities"
let chEnum = title.GetEnumerator()

printfn $"The length of the string is {title.Length} characters:"

let mutable outputLine1 = ""
let mutable outputLine2 = ""
let mutable outputLine3 = ""
let mutable i = 1

for ch in title do
    outputLine1 <- outputLine1 + if i < 10 || i % 10 <> 0 then "  " else $"{i / 10} "
    outputLine2 <- outputLine2 + $"{i % 10} ";
    outputLine3 <- outputLine3 + $"{ch} "
    i <- i + 1

printfn "%s" outputLine1
printfn "%s" outputLine2
printfn "%s" outputLine3

// The example displays the following output to the console:
//       The length of the string is 20 characters:
//                         1                   2
//       1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
//       A   T a l e   o f   T w o   C i t i e s
Dim title As String = "A Tale of Two Cities"
Dim ctr As Integer = 1
Dim outputLine1, outputLine2, outputLine3 As String 

For Each ch As Char In title
   outputLine1 += CStr(iif(ctr < 10 Or ctr Mod 10 <> 0, "  ", CStr(ctr \ 10) + " ")) 
   outputLine2 += (ctr Mod 10)& " "
   outputLine3 += ch & " "
   ctr += 1
Next

Console.WriteLine("The length of the string is {0} characters:", _
                  title.Length)
Console.WriteLine(outputLine1)
Console.WriteLine(outputLine2)    
Console.WriteLine(outputLine3)
' The example displays the following output to the console:      
'       The length of the string is 20 characters:
'                         1                   2
'       1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
'       A   T a l e   o f   T w o   C i t i e s

Комментарии

Предоставляет CharEnumerator доступ только для чтения к символам в объекте, на который String ссылается ссылка. Например, foreach инструкция языков программирования Microsoft Visual Basic и C#, которая выполняет итерацию элементов коллекции, извлекает CharEnumerator объект из String объекта для итерации символов в этом объекте.

Это важно

Класс CharEnumerator перечисляет отдельные 16-разрядные Char экземпляры. Он не рассматривает графемы (т. е. символы, за которыми следует один или несколько символов combiding) или суррогатные пары (т. е. символы за пределами базовой многоязычной плоскости Юникода) в качестве отдельных символов. Для перечислителя, обрабатывающего эти типы символов в виде одной единицы, используйте StringInfo класс.

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

Индекс CharEnumerator сохраняет внутренний индекс для символов в строке CharEnumerator ссылок. Недопустимое состояние индекса, если он ссылается на позицию символа логически до первого символа или после последнего символа в строке, и допустим, когда он ссылается на символ в строке. Индекс инициализируется в позицию логически до первого символа и устанавливается на позицию после последнего символа после завершения итерации. Исключение возникает, если вы пытаетесь получить доступ к символу, пока индекс недопустим.

Метод MoveNext увеличивает индекс по одному, поэтому к первым и последующим символам обращаются в свою очередь. Метод Reset задает индекс логическому расположению перед первым символом. Свойство Current извлекает символ, на который в данный момент ссылается индекс. Метод Clone создает копию CharEnumerator.

Замечание

Несколько независимых экземпляров CharEnumerator одного или нескольких потоков могут иметь доступ к одному экземпляру String. Этот класс реализуется для поддержки IEnumerator интерфейса. Дополнительные сведения об использовании перечислителя см. в IEnumerator разделе.

Свойства

Имя Описание
Current

Возвращает текущий знак, на который ссылается строка, перечисляемая этим CharEnumerator объектом.

Методы

Имя Описание
Clone()

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

Dispose()

Освобождает все ресурсы, используемые текущим экземпляром класса CharEnumerator.

Equals(Object)

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

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

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

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

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

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

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

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

Увеличивает внутренний индекс текущего CharEnumerator объекта к следующему символу перечисленной строки.

Reset()

Инициализирует индекс в положение логически перед первым символом перечисленной строки.

ToString()

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

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

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

Имя Описание
IDisposable.Dispose()

Освобождает все ресурсы, используемые классом CharEnumerator .

IEnumerator.Current

Возвращает текущий знак, на который ссылается строка, перечисляемая этим CharEnumerator объектом. Описание этого элемента см. в разделе Current.

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

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