UTF32Encoding.GetChars Método
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.
Descodifica uma sequência de bytes num conjunto de caracteres.
Sobrecargas
| Name | Description |
|---|---|
| GetChars(Byte*, Int32, Char*, Int32) |
Decodifica uma sequência de bytes a partir do ponteiro de byte especificado num conjunto de caracteres que são armazenados a partir do ponteiro especificado. |
| GetChars(Byte[], Int32, Int32, Char[], Int32) |
Descodifica uma sequência de bytes do array de bytes especificado para o array de caracteres especificado. |
GetChars(Byte*, Int32, Char*, Int32)
Importante
Esta API não está em conformidade com CLS.
Decodifica uma sequência de bytes a partir do ponteiro de byte especificado num conjunto de caracteres que são armazenados a partir do ponteiro especificado.
public:
override int GetChars(System::Byte* bytes, int byteCount, char* chars, int charCount);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public override int GetChars(byte* bytes, int byteCount, char* chars, int charCount);
[System.CLSCompliant(false)]
public override int GetChars(byte* bytes, int byteCount, char* chars, int charCount);
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
override this.GetChars : nativeptr<byte> * int * nativeptr<char> * int -> int
[<System.CLSCompliant(false)>]
override this.GetChars : nativeptr<byte> * int * nativeptr<char> * int -> int
Parâmetros
- bytes
- Byte*
Um apontador para o primeiro byte a descodificar.
- byteCount
- Int32
O número de bytes a descodificar.
- chars
- Char*
Um indicador para o local onde começar a escrever o conjunto resultante de caracteres.
- charCount
- Int32
O número máximo de caracteres para escrever.
Devoluções
O número real de caracteres escritos no local indicado por chars.
- Atributos
Exceções
byteCount ou charCount é inferior a zero.
A deteção de erros está ativada e bytes contém uma sequência inválida de bytes.
-ou-
charCount é inferior ao número resultante de caracteres.
Ocorreu um recurso de recurso (para mais informações, veja Codificação de Caracteres em .NET)
- e -
DecoderFallback está definido como DecoderExceptionFallback.
Observações
Para calcular o tamanho exato do array necessário GetChars para armazenar os caracteres resultantes, chama o GetCharCount método. Para calcular o tamanho máximo do array, chama o GetMaxCharCount método. O GetCharCount método geralmente aloca menos memória, enquanto o GetMaxCharCount método geralmente executa mais rapidamente.
Com a deteção de erros, uma sequência inválida faz com que este método execute um ArgumentException. Sem deteção de erros, as sequências inválidas são ignoradas e nenhuma exceção é lançada.
Se o intervalo de bytes a decodificar incluir a marca de ordem de bytes (BOM) e o array de bytes for devolvido por um método de tipo não conhecido pela BOM, o carácter U+FFFE é incluído no array de caracteres devolvido por este método. Podes removê-lo chamando o String.TrimStart método.
Os dados a converter, como dados lidos de um fluxo, podem estar disponíveis apenas em blocos sequenciais. Neste caso, ou se a quantidade de dados for tão grande que precisa de ser dividida em blocos mais pequenos, a aplicação utiliza o Decoder ou o Encoder fornecido pelo GetDecoder método ou pelo GetEncoder método, respetivamente.
Ver também
- GetCharCount(Byte[], Int32, Int32)
- GetMaxCharCount(Int32)
- GetDecoder()
- GetString(Byte[], Int32, Int32)
Aplica-se a
GetChars(Byte[], Int32, Int32, Char[], Int32)
Descodifica uma sequência de bytes do array de bytes especificado para o array de caracteres especificado.
public:
override int GetChars(cli::array <System::Byte> ^ bytes, int byteIndex, int byteCount, cli::array <char> ^ chars, int charIndex);
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex);
override this.GetChars : byte[] * int * int * char[] * int -> int
Public Overrides Function GetChars (bytes As Byte(), byteIndex As Integer, byteCount As Integer, chars As Char(), charIndex As Integer) As Integer
Parâmetros
- bytes
- Byte[]
O array de bytes que contém a sequência de bytes a decodificar.
- byteIndex
- Int32
O índice do primeiro byte a descodificar.
- byteCount
- Int32
O número de bytes a descodificar.
- chars
- Char[]
O array de caracteres para conter o conjunto resultante de caracteres.
- charIndex
- Int32
O índice a partir do qual começar a escrever o conjunto resultante de caracteres.
Devoluções
O número real de caracteres escritos em chars.
Exceções
byteIndex ou byteCount ou charIndex é menor que zero.
-ou-
byteIndex e byteCount não denotam um intervalo válido em bytes.
-ou-
charIndex não é um índice válido em chars.
A deteção de erros está ativada e bytes contém uma sequência inválida de bytes.
-ou-
chars não tem capacidade suficiente de charIndex até ao fim do array para acomodar os caracteres resultantes.
Ocorreu um recurso de recurso (para mais informações, veja Codificação de Caracteres em .NET)
- e -
DecoderFallback está definido como DecoderExceptionFallback.
Exemplos
O exemplo seguinte codifica uma string num array de bytes, e depois descodifica os bytes num array de caracteres.
using System;
using System.Text;
public class SamplesUTF32Encoding {
public static void Main() {
// Create two instances of UTF32Encoding: one with little-endian byte order and one with big-endian byte order.
UTF32Encoding u32LE = new UTF32Encoding( false, true, true );
UTF32Encoding u32BE = new UTF32Encoding( true, true, true );
// Create byte arrays from the same string containing the following characters:
// Latin Small Letter Z (U+007A)
// Latin Small Letter A (U+0061)
// Combining Breve (U+0306)
// Latin Small Letter AE With Acute (U+01FD)
// Greek Small Letter Beta (U+03B2)
// a high-surrogate value (U+D8FF)
// a low-surrogate value (U+DCFF)
String myStr = "za\u0306\u01FD\u03B2\uD8FF\uDCFF";
// barrBE uses the big-endian byte order.
byte[] barrBE = new byte[u32BE.GetByteCount( myStr )];
u32BE.GetBytes( myStr, 0, myStr.Length, barrBE, 0 );
// barrLE uses the little-endian byte order.
byte[] barrLE = new byte[u32LE.GetByteCount( myStr )];
u32LE.GetBytes( myStr, 0, myStr.Length, barrLE, 0 );
// Get the char counts and decode the byte arrays.
Console.Write( "BE array with BE encoding : " );
PrintCountsAndChars( barrBE, u32BE );
Console.Write( "LE array with LE encoding : " );
PrintCountsAndChars( barrLE, u32LE );
// Decode the byte arrays using an encoding with a different byte order.
Console.Write( "BE array with LE encoding : " );
try {
PrintCountsAndChars( barrBE, u32LE );
}
catch ( System.ArgumentException e ) {
Console.WriteLine( e.Message );
}
Console.Write( "LE array with BE encoding : " );
try {
PrintCountsAndChars( barrLE, u32BE );
}
catch ( System.ArgumentException e ) {
Console.WriteLine( e.Message );
}
}
public static void PrintCountsAndChars( byte[] bytes, Encoding enc ) {
// Display the name of the encoding used.
Console.Write( "{0,-25} :", enc.ToString() );
// Display the exact character count.
int iCC = enc.GetCharCount( bytes );
Console.Write( " {0,-3}", iCC );
// Display the maximum character count.
int iMCC = enc.GetMaxCharCount( bytes.Length );
Console.Write( " {0,-3} :", iMCC );
// Decode the bytes and display the characters.
char[] chars = new char[iCC];
enc.GetChars( bytes, 0, bytes.Length, chars, 0 );
Console.WriteLine( chars );
}
}
Imports System.Text
Public Class SamplesUTF32Encoding
Public Shared Sub Main()
' Create two instances of UTF32Encoding: one with little-endian byte order and one with big-endian byte order.
Dim u32LE As New UTF32Encoding(False, True, True)
Dim u32BE As New UTF32Encoding(True, True, True)
' Create byte arrays from the same string containing the following characters:
' Latin Small Letter Z (U+007A)
' Latin Small Letter A (U+0061)
' Combining Breve (U+0306)
' Latin Small Letter AE With Acute (U+01FD)
' Greek Small Letter Beta (U+03B2)
' a high-surrogate value (U+D8FF)
' a low-surrogate value (U+DCFF)
Dim myStr As String = "za" & ChrW(&H0306) & ChrW(&H01FD) & ChrW(&H03B2) & ChrW(&HD8FF) & ChrW(&HDCFF)
' barrBE uses the big-endian byte order.
' NOTE: In Visual Basic, arrays contain one extra element by default.
' The following line creates an array with the exact number of elements required.
Dim barrBE(u32BE.GetByteCount(myStr) - 1) As Byte
u32BE.GetBytes(myStr, 0, myStr.Length, barrBE, 0)
' barrLE uses the little-endian byte order.
' NOTE: In Visual Basic, arrays contain one extra element by default.
' The following line creates an array with the exact number of elements required.
Dim barrLE(u32LE.GetByteCount(myStr) - 1) As Byte
u32LE.GetBytes(myStr, 0, myStr.Length, barrLE, 0)
' Get the char counts and decode the byte arrays.
Console.Write("BE array with BE encoding : ")
PrintCountsAndChars(barrBE, u32BE)
Console.Write("LE array with LE encoding : ")
PrintCountsAndChars(barrLE, u32LE)
' Decode the byte arrays using an encoding with a different byte order.
Console.Write("BE array with LE encoding : ")
Try
PrintCountsAndChars(barrBE, u32LE)
Catch e As System.ArgumentException
Console.WriteLine(e.Message)
End Try
Console.Write("LE array with BE encoding : ")
Try
PrintCountsAndChars(barrLE, u32BE)
Catch e As System.ArgumentException
Console.WriteLine(e.Message)
End Try
End Sub
Public Shared Sub PrintCountsAndChars(bytes() As Byte, enc As Encoding)
' Display the name of the encoding used.
Console.Write("{0,-25} :", enc.ToString())
' Display the exact character count.
Dim iCC As Integer = enc.GetCharCount(bytes)
Console.Write(" {0,-3}", iCC)
' Display the maximum character count.
Dim iMCC As Integer = enc.GetMaxCharCount(bytes.Length)
Console.Write(" {0,-3} :", iMCC)
' Decode the bytes and display the characters.
Dim chars(iCC) As Char
enc.GetChars(bytes, 0, bytes.Length, chars, 0)
Console.WriteLine(chars)
End Sub
End Class
Observações
Para calcular o tamanho exato do array necessário GetChars para armazenar os caracteres resultantes, chama o GetCharCount método. Para calcular o tamanho máximo do array, chama o GetMaxCharCount método. O GetCharCount método geralmente aloca menos memória, enquanto o GetMaxCharCount método geralmente executa mais rapidamente.
Com a deteção de erros, uma sequência inválida faz com que este método execute um ArgumentException. Sem deteção de erros, as sequências inválidas são ignoradas e nenhuma exceção é lançada.
Se o intervalo de bytes a decodificar incluir a marca de ordem de bytes (BOM) e o array de bytes for devolvido por um método de tipo não conhecido pela BOM, o carácter U+FFFE é incluído no array de caracteres devolvido por este método. Podes removê-lo chamando o String.TrimStart método.
Os dados a converter, como dados lidos de um fluxo, podem estar disponíveis apenas em blocos sequenciais. Neste caso, ou se a quantidade de dados for tão grande que precisa de ser dividida em blocos mais pequenos, a aplicação utiliza o Decoder ou o Encoder fornecido pelo GetDecoder método ou pelo GetEncoder método, respetivamente.
Ver também
- GetCharCount(Byte[], Int32, Int32)
- GetMaxCharCount(Int32)
- GetDecoder()
- GetString(Byte[], Int32, Int32)