CharEnumerator Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Suporta iterar sobre um String objeto e ler os seus caracteres individuais. Esta classe não pode ser herdada.
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
- Herança
-
CharEnumerator
- Atributos
- Implementações
Exemplos
O exemplo seguinte usa a CharEnumerator classe para enumerar os caracteres individuais numa cadeia. Instancia um CharEnumerator objeto ao chamar o String.GetEnumerator método, move-se de um carácter para o seguinte ao chamar o MoveNext método, e apresenta o carácter atual ao recuperar o valor da Current propriedade.
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
Note-se, no entanto, que a mesma operação pode ser realizada de forma um pouco mais intuitiva usando foreach (em C#) ou For Each (em Visual Basic), como mostra o exemplo seguinte.
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
Observações
A CharEnumerator fornece acesso apenas de leitura aos caracteres num objeto referenciado String . Por exemplo, a instrução foreach das linguagens de programação Microsoft Visual Basic e C#, que itera pelos elementos de uma coleção, recupera um CharEnumerator de um objeto String para iterar pelos caracteres desse objeto.
Importante
A CharEnumerator classe enumera instâncias individuais de 16 bits Char . Não considera grafemas (isto é, um carácter seguido de um ou mais caracteres compulsivos) ou pares substitutos (isto é, caracteres fora do Plano Multilíngue Básico Unicode) como caracteres únicos. Para um enumerador que lide com estes tipos de caracteres como uma única unidade, use a StringInfo classe.
Não existe um construtor público para CharEnumerator. Em vez disso, chama-se o método de String um GetEnumerator objeto para obter um CharEnumerator que está inicializado para referenciar a cadeia.
A CharEnumerator mantém um índice interno para os caracteres na cadeia de referências CharEnumerator . O estado do índice é inválido quando faz referência lógica a uma posição de carácter antes do primeiro ou depois do último carácter da cadeia, e válido quando faz referência a um carácter dentro da cadeia. O índice é inicializado para uma posição logicamente anterior ao primeiro caractere, e é definido para uma posição após o último carácter quando a iteração está concluída. Uma exceção é lançada se tentar aceder a um carácter enquanto o índice está inválido.
O MoveNext método incrementa o índice em um, de modo que o primeiro e os caracteres seguintes são acedidos por sua vez. O Reset método define o índice para uma posição lógica anterior ao primeiro carácter. A Current propriedade recupera o carácter atualmente referenciado pelo índice. O Clone método cria uma cópia do CharEnumerator.
Note
Várias instâncias independentes de CharEnumerator entre uma ou mais threads podem ter acesso a uma única instância de String. Esta classe está implementada para suportar a IEnumerator interface. Para mais informações sobre o uso de um enumerador, consulte o IEnumerator tópico.
Propriedades
| Name | Description |
|---|---|
| Current |
Obtém o carácter atualmente referenciado na cadeia enumerada por este CharEnumerator objeto. |
Métodos
| Name | Description |
|---|---|
| Clone() |
Cria uma cópia do objeto atual CharEnumerator . |
| Dispose() |
Liberta todos os recursos usados pela instância atual da CharEnumerator classe. |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| MoveNext() |
Incrementa o índice interno do objeto atual CharEnumerator para o próximo carácter da cadeia enumerada. |
| Reset() |
Inicializa o índice para uma posição logicamente anterior ao primeiro carácter da cadeia enumerada. |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |
Implementações de Interface Explícita
| Name | Description |
|---|---|
| IDisposable.Dispose() |
Liberta todos os recursos usados pela CharEnumerator turma. |
| IEnumerator.Current |
Obtém o carácter atualmente referenciado na cadeia enumerada por este CharEnumerator objeto. Para uma descrição deste elemento, veja Current. |