Encoding.GetChars Metoda

Definicja

Po przesłonięciu w klasie pochodnej sekwencja bajtów jest dekodowana do zestawu znaków.

Przeciążenia

GetChars(Byte[], Int32, Int32, Char[], Int32)

Po zastąpieniu w klasie pochodnej dekoduje sekwencję bajtów z określonej tablicy bajtów do określonej tablicy znaków.

GetChars(Byte*, Int32, Char*, Int32)

Po zastąpieniu w klasie pochodnej dekoduje sekwencję bajtów rozpoczynających się od określonego wskaźnika bajtów do zestawu znaków, które są przechowywane począwszy od określonego wskaźnika znaku.

GetChars(Byte[], Int32, Int32)

Po zastąpieniu w klasie pochodnej dekoduje sekwencję bajtów z określonej tablicy bajtów do zestawu znaków.

GetChars(ReadOnlySpan<Byte>, Span<Char>)

Po zastąpieniu w klasie pochodnej dekoduje wszystkie bajty w określonym zakresie bajtów tylko do odczytu w zakresie znaków.

GetChars(Byte[])

Po przesłonięciu w klasie pochodnej wszystkie bajty w określonej tablicy bajtów są dekodowane w zestawie znaków.

GetChars(Byte[], Int32, Int32, Char[], Int32)

Po zastąpieniu w klasie pochodnej dekoduje sekwencję bajtów z określonej tablicy bajtów do określonej tablicy znaków.

public:
 abstract int GetChars(cli::array <System::Byte> ^ bytes, int byteIndex, int byteCount, cli::array <char> ^ chars, int charIndex);
public abstract int GetChars (byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex);
abstract member GetChars : byte[] * int * int * char[] * int -> int
Public MustOverride Function GetChars (bytes As Byte(), byteIndex As Integer, byteCount As Integer, chars As Char(), charIndex As Integer) As Integer

Parametry

bytes
Byte[]

Tablica bajtów zawierająca sekwencję bajtów do dekodowania.

byteIndex
Int32

Indeks pierwszego bajtu do dekodowania.

byteCount
Int32

Liczba bajtów do dekodowania.

chars
Char[]

Tablica znaków zawierająca wynikowy zestaw znaków.

charIndex
Int32

Indeks, w którym należy rozpocząć pisanie wynikowego zestawu znaków.

Zwraca

Rzeczywista liczba znaków zapisanych w pliku chars.

Wyjątki

bytes to null.

-lub-

chars to null.

byteIndex lub byteCountcharIndex jest mniejsza niż zero.

-lub-

byteindex i byteCount nie oznaczają prawidłowego zakresu w elemecie bytes.

-lub-

charIndex nie jest prawidłowym indeksem w pliku chars.

chars nie ma wystarczającej pojemności od charIndex do końca tablicy, aby pomieścić wynikowe znaki.

Wystąpił powrót (aby uzyskać więcej informacji, zobacz Kodowanie znaków na platformie .NET)

-I-

DecoderFallback parametr jest ustawiony na DecoderExceptionFallbackwartość .

Przykłady

Poniższy przykład konwertuje ciąg z jednego kodowania na inny.

using namespace System;
using namespace System::Text;

int main()
{
   String^ unicodeString = "This string contains the unicode character Pi (\u03a0)";
   
   // Create two different encodings.
   Encoding^ ascii = Encoding::ASCII;
   Encoding^ unicode = Encoding::Unicode;
   
   // Convert the string into a byte array.
   array<Byte>^unicodeBytes = unicode->GetBytes( unicodeString );
   
   // Perform the conversion from one encoding to the other.
   array<Byte>^asciiBytes = Encoding::Convert( unicode, ascii, unicodeBytes );
   
   // Convert the new Byte into[] a char and[] then into a string.
   array<Char>^asciiChars = gcnew array<Char>(ascii->GetCharCount( asciiBytes, 0, asciiBytes->Length ));
   ascii->GetChars( asciiBytes, 0, asciiBytes->Length, asciiChars, 0 );
   String^ asciiString = gcnew String( asciiChars );
   
   // Display the strings created before and after the conversion.
   Console::WriteLine( "Original String*: {0}", unicodeString );
   Console::WriteLine( "Ascii converted String*: {0}", asciiString );
}
// The example displays the following output:
//    Original string: This string contains the unicode character Pi (Π)
//    Ascii converted string: This string contains the unicode character Pi (?)
using System;
using System.Text;

class Example
{
   static void Main()
   {
      string unicodeString = "This string contains the unicode character Pi (\u03a0)";

      // Create two different encodings.
      Encoding ascii = Encoding.ASCII;
      Encoding unicode = Encoding.Unicode;

      // Convert the string into a byte array.
      byte[] unicodeBytes = unicode.GetBytes(unicodeString);

      // Perform the conversion from one encoding to the other.
      byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);
         
      // Convert the new byte[] into a char[] and then into a string.
      char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
      ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
      string asciiString = new string(asciiChars);

      // Display the strings created before and after the conversion.
      Console.WriteLine("Original string: {0}", unicodeString);
      Console.WriteLine("Ascii converted string: {0}", asciiString);
   }
}
// The example displays the following output:
//    Original string: This string contains the unicode character Pi (Π)
//    Ascii converted string: This string contains the unicode character Pi (?)
Imports System.Text

Class Example
   Shared Sub Main()
      Dim unicodeString As String = "This string contains the unicode character Pi (" & ChrW(&H03A0) & ")"

      ' Create two different encodings.
      Dim ascii As Encoding = Encoding.ASCII
      Dim unicode As Encoding = Encoding.Unicode

      ' Convert the string into a byte array.
      Dim unicodeBytes As Byte() = unicode.GetBytes(unicodeString)

      ' Perform the conversion from one encoding to the other.
      Dim asciiBytes As Byte() = Encoding.Convert(unicode, ascii, unicodeBytes)

      ' Convert the new byte array into a char array and then into a string.
      Dim asciiChars(ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)-1) As Char
      ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0)
      Dim asciiString As New String(asciiChars)

      ' Display the strings created before and after the conversion.
      Console.WriteLine("Original string: {0}", unicodeString)
      Console.WriteLine("Ascii converted string: {0}", asciiString)
   End Sub
End Class
' The example displays the following output:
'    Original string: This string contains the unicode character Pi (Π)
'    Ascii converted string: This string contains the unicode character Pi (?)

Poniższy przykład koduje ciąg do tablicy bajtów, a następnie dekoduje zakres bajtów do tablicy znaków.

using namespace System;
using namespace System::Text;
void PrintCountsAndChars( array<Byte>^bytes, int index, int count, Encoding^ enc );
int main()
{
   
   // Create two instances of UTF32Encoding: one with little-endian byte order and one with big-endian byte order.
   Encoding^ u32LE = Encoding::GetEncoding( "utf-32" );
   Encoding^ u32BE = Encoding::GetEncoding( "utf-32BE" );
   
   // Use a 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)
   String^ myStr = "za\u0306\u01FD\u03B2";
   
   // Encode the string using the big-endian byte order.
   array<Byte>^barrBE = gcnew array<Byte>(u32BE->GetByteCount( myStr ));
   u32BE->GetBytes( myStr, 0, myStr->Length, barrBE, 0 );
   
   // Encode the string using the little-endian byte order.
   array<Byte>^barrLE = gcnew array<Byte>(u32LE->GetByteCount( myStr ));
   u32LE->GetBytes( myStr, 0, myStr->Length, barrLE, 0 );
   
   // Get the char counts, decode eight bytes starting at index 0,
   // and print out the counts and the resulting bytes.
   Console::Write( "BE array with BE encoding : " );
   PrintCountsAndChars( barrBE, 0, 8, u32BE );
   Console::Write( "LE array with LE encoding : " );
   PrintCountsAndChars( barrLE, 0, 8, u32LE );
}

void PrintCountsAndChars( array<Byte>^bytes, int index, int count, Encoding^ enc )
{
   
   // Display the name of the encoding used.
   Console::Write( "{0,-25} :", enc );
   
   // Display the exact character count.
   int iCC = enc->GetCharCount( bytes, index, count );
   Console::Write( " {0,-3}", iCC );
   
   // Display the maximum character count.
   int iMCC = enc->GetMaxCharCount( count );
   Console::Write( " {0,-3} :", iMCC );
   
   // Decode the bytes and display the characters.
   array<Char>^chars = enc->GetChars( bytes, index, count );
   
   // The following is an alternative way to decode the bytes:
   // Char[] chars = new Char[iCC];
   // enc->GetChars( bytes, index, count, chars, 0 );
   Console::WriteLine( chars );
}

/* 
This code produces the following output.  The question marks take the place of characters that cannot be displayed at the console.

BE array with BE encoding : System.Text.UTF32Encoding : 2   6   :za
LE array with LE encoding : System.Text.UTF32Encoding : 2   6   :za

*/
using System;
using System.Text;

public class SamplesEncoding  {

   public static void Main()  {

      // Create two instances of UTF32Encoding: one with little-endian byte order and one with big-endian byte order.
      Encoding u32LE = Encoding.GetEncoding( "utf-32" );
      Encoding u32BE = Encoding.GetEncoding( "utf-32BE" );

      // Use a 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)
      String myStr = "za\u0306\u01FD\u03B2";

      // Encode the string using the big-endian byte order.
      byte[] barrBE = new byte[u32BE.GetByteCount( myStr )];
      u32BE.GetBytes( myStr, 0, myStr.Length, barrBE, 0 );

      // Encode the string using the little-endian byte order.
      byte[] barrLE = new byte[u32LE.GetByteCount( myStr )];
      u32LE.GetBytes( myStr, 0, myStr.Length, barrLE, 0 );

      // Get the char counts, decode eight bytes starting at index 0,
      // and print out the counts and the resulting bytes.
      Console.Write( "BE array with BE encoding : " );
      PrintCountsAndChars( barrBE, 0, 8, u32BE );
      Console.Write( "LE array with LE encoding : " );
      PrintCountsAndChars( barrLE, 0, 8, u32LE );
   }

   public static void PrintCountsAndChars( byte[] bytes, int index, int count, 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, index, count );
      Console.Write( " {0,-3}", iCC );

      // Display the maximum character count.
      int iMCC = enc.GetMaxCharCount( count );
      Console.Write( " {0,-3} :", iMCC );

      // Decode the bytes and display the characters.
      char[] chars = enc.GetChars( bytes, index, count );

      // The following is an alternative way to decode the bytes:
      // char[] chars = new char[iCC];
      // enc.GetChars( bytes, index, count, chars, 0 );

      Console.WriteLine( chars );
   }
}


/* 
This code produces the following output.  The question marks take the place of characters that cannot be displayed at the console.

BE array with BE encoding : System.Text.UTF32Encoding : 2   6   :za
LE array with LE encoding : System.Text.UTF32Encoding : 2   6   :za

*/
Imports System.Text

Public Class SamplesEncoding   

   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 Encoding = Encoding.GetEncoding("utf-32")
      Dim u32BE As Encoding = Encoding.GetEncoding("utf-32BE")

      ' Use a 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)
      Dim myStr As String = "za" & ChrW(&H0306) & ChrW(&H01FD) & ChrW(&H03B2)

      ' Encode the string using the big-endian byte order.
      ' NOTE: In VB.NET, arrays contain one extra element by default.
      '       The following line creates barrBE with the exact number of elements required.
      Dim barrBE(u32BE.GetByteCount(myStr) - 1) As Byte
      u32BE.GetBytes(myStr, 0, myStr.Length, barrBE, 0)

      ' Encode the string using the little-endian byte order.
      ' NOTE: In VB.NET, arrays contain one extra element by default.
      '       The following line creates barrLE 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, decode eight bytes starting at index 0,
      ' and print out the counts and the resulting bytes.
      Console.Write("BE array with BE encoding : ")
      PrintCountsAndChars(barrBE, 0, 8, u32BE)
      Console.Write("LE array with LE encoding : ")
      PrintCountsAndChars(barrLE, 0, 8, u32LE)

   End Sub


   Public Shared Sub PrintCountsAndChars(bytes() As Byte, index As Integer, count As Integer, 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, index, count)
      Console.Write(" {0,-3}", iCC)

      ' Display the maximum character count.
      Dim iMCC As Integer = enc.GetMaxCharCount(count)
      Console.Write(" {0,-3} :", iMCC)

      ' Decode the bytes.
      Dim chars As Char() = enc.GetChars(bytes, index, count)

      ' The following is an alternative way to decode the bytes:
      ' NOTE: In VB.NET, arrays contain one extra element by default.
      '       The following line creates the array with the exact number of elements required.
      ' Dim chars(iCC - 1) As Char
      ' enc.GetChars( bytes, index, count, chars, 0 )

      ' Display the characters.
      Console.WriteLine(chars)

   End Sub

End Class


'This code produces the following output.  The question marks take the place of characters that cannot be displayed at the console.
'
'BE array with BE encoding : System.Text.UTF32Encoding : 2   6   :za
'LE array with LE encoding : System.Text.UTF32Encoding : 2   6   :za

Uwagi

Aby obliczyć dokładny rozmiar tablicy wymagany przez GetChars program do przechowywania znaków wynikowych, należy użyć GetCharCount metody . Aby obliczyć maksymalny rozmiar tablicy, użyj GetMaxCharCount metody . Metoda GetCharCount zwykle zezwala na alokację mniejszej ilości pamięci, podczas gdy GetMaxCharCount metoda zwykle wykonuje się szybciej.

GetChars(Byte[], Int32, Int32, Char[], Int32) pobiera znaki z sekwencji bajtów wejściowych. Encoding.GetChars jest inna niż Decoder.GetChars dlatego, że Encoding oczekuje dyskretnych konwersji, podczas gdy Decoder jest przeznaczony dla wielu przechodzi na jednym strumieniu wejściowym.

Jeśli dane, które mają zostać przekonwertowane, są dostępne tylko w blokach sekwencyjnych (takich jak dane odczytane ze strumienia) lub jeśli ilość danych jest tak duża, że należy podzielić je na mniejsze bloki, należy użyć Decoder metody lub Encoder dostarczonej przez GetDecoder metodę lub GetEncoder metodę, odpowiednio, klasy pochodnej.

Uwaga

Ta metoda ma działać na znakach Unicode, a nie na dowolnych danych binarnych, takich jak tablice bajtów. Jeśli musisz zakodować dowolne dane binarne do tekstu, należy użyć protokołu takiego jak uuencode, który jest implementowany za pomocą metod, takich jak Convert.ToBase64CharArray.

Metoda GetCharCount określa, ile znaków powoduje dekodowanie sekwencji bajtów, a GetChars metoda wykonuje rzeczywiste dekodowanie. Metoda Encoding.GetChars oczekuje dyskretnych konwersji, w przeciwieństwie do Decoder.GetChars metody, która obsługuje wiele przechodzi w jednym strumieniu wejściowym.

Obsługiwane są różne wersje GetCharCount programu i GetChars . Poniżej przedstawiono kilka zagadnień programistycznych dotyczących używania tych metod:

  • Aplikacja może wymagać dekodowania wielu bajtów wejściowych ze strony kodu i przetworzenia bajtów przy użyciu wielu wywołań. W takim przypadku prawdopodobnie trzeba zachować stan między wywołaniami, ponieważ sekwencje bajtów mogą zostać przerwane podczas przetwarzania w partiach. (Na przykład część sekwencji przesunięcia ISO-2022 może zakończyć jedno GetChars wywołanie i kontynuować na początku następnego GetChars wywołania. Encoding.GetChars Wywoła rezerwę dla tych niekompletnych sekwencji, ale Decoder zapamięta te sekwencje dla następnego wywołania).

  • Jeśli aplikacja obsługuje dane wyjściowe ciągu, zalecana GetString jest metoda . Ponieważ ta metoda musi sprawdzić długość ciągu i przydzielić bufor, jest nieco wolniejsza, ale wynikowy String typ ma być preferowany.

  • Wersja bajtów programu GetChars(Byte*, Int32, Char*, Int32) umożliwia szybkie techniki, szczególnie w przypadku wielu wywołań do dużych buforów. Należy jednak pamiętać, że ta wersja metody jest czasami niebezpieczna, ponieważ wymagane są wskaźniki.

  • Jeśli aplikacja musi przekonwertować dużą ilość danych, powinna ponownie użyć buforu wyjściowego. W takim przypadku najlepszym wyborem jest wersja obsługująca GetChars(Byte[], Int32, Int32, Char[], Int32) bufory znaków wyjściowych.

  • Rozważ użycie Decoder.Convert metody zamiast GetCharCount. Metoda konwersji konwertuje jak najwięcej danych i zgłasza wyjątek, jeśli bufor wyjściowy jest zbyt mały. W przypadku ciągłego dekodowania strumienia ta metoda jest często najlepszym wyborem.

Zobacz też

Dotyczy

GetChars(Byte*, Int32, Char*, Int32)

Ważne

Ten interfejs API nie jest zgodny ze specyfikacją CLS.

W przypadku zastąpienia w klasie pochodnej dekoduje sekwencję bajtów rozpoczynającą się od określonego wskaźnika bajtów do zestawu znaków przechowywanych w określonym wskaźniku znaków.

public:
 virtual int GetChars(System::Byte* bytes, int byteCount, char* chars, int charCount);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public virtual int GetChars (byte* bytes, int byteCount, char* chars, int charCount);
[System.CLSCompliant(false)]
public virtual int GetChars (byte* bytes, int byteCount, char* chars, int charCount);
[System.CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual int GetChars (byte* bytes, int byteCount, char* chars, int charCount);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual int GetChars (byte* bytes, int byteCount, char* chars, int charCount);
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
abstract member GetChars : nativeptr<byte> * int * nativeptr<char> * int -> int
override this.GetChars : nativeptr<byte> * int * nativeptr<char> * int -> int
[<System.CLSCompliant(false)>]
abstract member GetChars : nativeptr<byte> * int * nativeptr<char> * int -> int
override this.GetChars : nativeptr<byte> * int * nativeptr<char> * int -> int
[<System.CLSCompliant(false)>]
[<System.Runtime.InteropServices.ComVisible(false)>]
abstract member GetChars : nativeptr<byte> * int * nativeptr<char> * int -> int
override this.GetChars : nativeptr<byte> * int * nativeptr<char> * int -> int
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
[<System.Runtime.InteropServices.ComVisible(false)>]
abstract member GetChars : nativeptr<byte> * int * nativeptr<char> * int -> int
override this.GetChars : nativeptr<byte> * int * nativeptr<char> * int -> int

Parametry

bytes
Byte*

Wskaźnik do pierwszego bajtu w celu dekodowania.

byteCount
Int32

Liczba bajtów do dekodowania.

chars
Char*

Wskaźnik do lokalizacji, w której należy rozpocząć pisanie wynikowego zestawu znaków.

charCount
Int32

Maksymalna liczba znaków do zapisania.

Zwraca

Rzeczywista liczba znaków zapisanych w lokalizacji wskazanej chars przez parametr .

Atrybuty

Wyjątki

bytes to null.

-lub-

chars to null.

byteCount wartość lub charCount jest mniejsza niż zero.

charCount jest mniejsza niż wynikowa liczba znaków.

Wystąpił powrót (aby uzyskać więcej informacji, zobacz Kodowanie znaków na platformie .NET)

-I-

DecoderFallback parametr jest ustawiony na DecoderExceptionFallbackwartość .

Uwagi

Aby obliczyć dokładny rozmiar tablicy, który GetChars wymaga przechowywania znaków wynikowych, należy użyć GetCharCount metody . Aby obliczyć maksymalny rozmiar tablicy, użyj GetMaxCharCount metody . Metoda GetCharCount zwykle zezwala na alokację mniejszej ilości pamięci, podczas gdy GetMaxCharCount metoda zwykle wykonuje się szybciej.

Encoding.GetChars pobiera znaki z sekwencji bajtów wejściowych. Encoding.GetChars jest inna niż Decoder.GetChars dlatego, że Encoding oczekuje dyskretnych konwersji, podczas gdy Decoder jest przeznaczony dla wielu przechodzi na jednym strumieniu wejściowym.

Jeśli dane do konwersji są dostępne tylko w blokach sekwencyjnych (takich jak dane odczytane ze strumienia) lub jeśli ilość danych jest tak duża, że należy podzielić je na mniejsze bloki, należy użyć Decoder obiektu lub dostarczonego przez GetDecoder metodę lub EncoderGetEncoder, odpowiednio, klasy pochodnej.

Uwaga

Ta metoda ma działać na znakach Unicode, a nie na dowolnych danych binarnych, takich jak tablice bajtów. Jeśli musisz zakodować dowolne dane binarne do tekstu, należy użyć protokołu takiego jak uuencode, który jest implementowany za pomocą metod, takich jak Convert.ToBase64CharArray.

Metoda GetCharCount określa, ile znaków powoduje dekodowanie sekwencji bajtów, a GetChars metoda wykonuje rzeczywiste dekodowanie. Metoda Encoding.GetChars oczekuje dyskretnych konwersji, w przeciwieństwie do Decoder.GetChars metody, która obsługuje wiele przechodzi w jednym strumieniu wejściowym.

Obsługiwane są różne wersje GetCharCount programu i GetChars . Poniżej przedstawiono kilka zagadnień programistycznych dotyczących używania tych metod:

  • Aplikacja może wymagać dekodowania wielu bajtów wejściowych ze strony kodu i przetworzenia bajtów przy użyciu wielu wywołań. W takim przypadku prawdopodobnie trzeba zachować stan między wywołaniami, ponieważ sekwencje bajtów mogą zostać przerwane podczas przetwarzania w partiach. (Na przykład część sekwencji przesunięcia ISO-2022 może zakończyć jedno GetChars wywołanie i kontynuować na początku następnego GetChars wywołania. Encoding.GetChars Wywoła rezerwę dla tych niekompletnych sekwencji, ale Decoder zapamięta te sekwencje dla następnego wywołania).

  • Jeśli aplikacja obsługuje dane wyjściowe ciągu, zalecana GetString jest metoda . Ponieważ ta metoda musi sprawdzić długość ciągu i przydzielić bufor, jest nieco wolniejsza, ale wynikowy String typ ma być preferowany.

  • Wersja bajtów programu GetChars(Byte*, Int32, Char*, Int32) umożliwia szybkie techniki, szczególnie w przypadku wielu wywołań do dużych buforów. Należy jednak pamiętać, że ta wersja metody jest czasami niebezpieczna, ponieważ wymagane są wskaźniki.

  • Jeśli aplikacja musi przekonwertować dużą ilość danych, powinna ponownie użyć buforu wyjściowego. W takim przypadku najlepszym wyborem jest wersja obsługująca GetChars(Byte[], Int32, Int32, Char[], Int32) bufory znaków wyjściowych.

  • Rozważ użycie Decoder.Convert metody zamiast GetCharCount. Metoda konwersji konwertuje jak najwięcej danych i zgłasza wyjątek, jeśli bufor wyjściowy jest zbyt mały. W przypadku ciągłego dekodowania strumienia ta metoda jest często najlepszym wyborem.

Zobacz też

Dotyczy

GetChars(Byte[], Int32, Int32)

Po zastąpieniu w klasie pochodnej dekoduje sekwencję bajtów z określonej tablicy bajtów do zestawu znaków.

public:
 virtual cli::array <char> ^ GetChars(cli::array <System::Byte> ^ bytes, int index, int count);
public virtual char[] GetChars (byte[] bytes, int index, int count);
abstract member GetChars : byte[] * int * int -> char[]
override this.GetChars : byte[] * int * int -> char[]
Public Overridable Function GetChars (bytes As Byte(), index As Integer, count As Integer) As Char()

Parametry

bytes
Byte[]

Tablica bajtów zawierająca sekwencję bajtów do dekodowania.

index
Int32

Indeks pierwszego bajtu do dekodowania.

count
Int32

Liczba bajtów do dekodowania.

Zwraca

Char[]

Tablica znaków zawierająca wyniki dekodowania określonej sekwencji bajtów.

Wyjątki

bytes to null.

index wartość lub count jest mniejsza niż zero.

-lub-

index i count nie oznaczają prawidłowego zakresu w byteselemecie .

Wystąpił rezerwowy (aby uzyskać więcej informacji, zobacz Kodowanie znaków na platformie .NET)

-I-

DecoderFallback jest ustawiona na DecoderExceptionFallbackwartość .

Przykłady

Poniższy przykład koduje ciąg do tablicy bajtów, a następnie dekoduje zakres bajtów do tablicy znaków.

using namespace System;
using namespace System::Text;
void PrintCountsAndChars( array<Byte>^bytes, int index, int count, Encoding^ enc );
int main()
{
   
   // Create two instances of UTF32Encoding: one with little-endian byte order and one with big-endian byte order.
   Encoding^ u32LE = Encoding::GetEncoding( "utf-32" );
   Encoding^ u32BE = Encoding::GetEncoding( "utf-32BE" );
   
   // Use a 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)
   String^ myStr = "za\u0306\u01FD\u03B2";
   
   // Encode the string using the big-endian byte order.
   array<Byte>^barrBE = gcnew array<Byte>(u32BE->GetByteCount( myStr ));
   u32BE->GetBytes( myStr, 0, myStr->Length, barrBE, 0 );
   
   // Encode the string using the little-endian byte order.
   array<Byte>^barrLE = gcnew array<Byte>(u32LE->GetByteCount( myStr ));
   u32LE->GetBytes( myStr, 0, myStr->Length, barrLE, 0 );
   
   // Get the char counts, decode eight bytes starting at index 0,
   // and print out the counts and the resulting bytes.
   Console::Write( "BE array with BE encoding : " );
   PrintCountsAndChars( barrBE, 0, 8, u32BE );
   Console::Write( "LE array with LE encoding : " );
   PrintCountsAndChars( barrLE, 0, 8, u32LE );
}

void PrintCountsAndChars( array<Byte>^bytes, int index, int count, Encoding^ enc )
{
   
   // Display the name of the encoding used.
   Console::Write( "{0,-25} :", enc );
   
   // Display the exact character count.
   int iCC = enc->GetCharCount( bytes, index, count );
   Console::Write( " {0,-3}", iCC );
   
   // Display the maximum character count.
   int iMCC = enc->GetMaxCharCount( count );
   Console::Write( " {0,-3} :", iMCC );
   
   // Decode the bytes and display the characters.
   array<Char>^chars = enc->GetChars( bytes, index, count );
   
   // The following is an alternative way to decode the bytes:
   // Char[] chars = new Char[iCC];
   // enc->GetChars( bytes, index, count, chars, 0 );
   Console::WriteLine( chars );
}

/* 
This code produces the following output.  The question marks take the place of characters that cannot be displayed at the console.

BE array with BE encoding : System.Text.UTF32Encoding : 2   6   :za
LE array with LE encoding : System.Text.UTF32Encoding : 2   6   :za

*/
using System;
using System.Text;

public class SamplesEncoding  {

   public static void Main()  {

      // Create two instances of UTF32Encoding: one with little-endian byte order and one with big-endian byte order.
      Encoding u32LE = Encoding.GetEncoding( "utf-32" );
      Encoding u32BE = Encoding.GetEncoding( "utf-32BE" );

      // Use a 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)
      String myStr = "za\u0306\u01FD\u03B2";

      // Encode the string using the big-endian byte order.
      byte[] barrBE = new byte[u32BE.GetByteCount( myStr )];
      u32BE.GetBytes( myStr, 0, myStr.Length, barrBE, 0 );

      // Encode the string using the little-endian byte order.
      byte[] barrLE = new byte[u32LE.GetByteCount( myStr )];
      u32LE.GetBytes( myStr, 0, myStr.Length, barrLE, 0 );

      // Get the char counts, decode eight bytes starting at index 0,
      // and print out the counts and the resulting bytes.
      Console.Write( "BE array with BE encoding : " );
      PrintCountsAndChars( barrBE, 0, 8, u32BE );
      Console.Write( "LE array with LE encoding : " );
      PrintCountsAndChars( barrLE, 0, 8, u32LE );
   }

   public static void PrintCountsAndChars( byte[] bytes, int index, int count, 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, index, count );
      Console.Write( " {0,-3}", iCC );

      // Display the maximum character count.
      int iMCC = enc.GetMaxCharCount( count );
      Console.Write( " {0,-3} :", iMCC );

      // Decode the bytes and display the characters.
      char[] chars = enc.GetChars( bytes, index, count );

      // The following is an alternative way to decode the bytes:
      // char[] chars = new char[iCC];
      // enc.GetChars( bytes, index, count, chars, 0 );

      Console.WriteLine( chars );
   }
}


/* 
This code produces the following output.  The question marks take the place of characters that cannot be displayed at the console.

BE array with BE encoding : System.Text.UTF32Encoding : 2   6   :za
LE array with LE encoding : System.Text.UTF32Encoding : 2   6   :za

*/
Imports System.Text

Public Class SamplesEncoding   

   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 Encoding = Encoding.GetEncoding("utf-32")
      Dim u32BE As Encoding = Encoding.GetEncoding("utf-32BE")

      ' Use a 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)
      Dim myStr As String = "za" & ChrW(&H0306) & ChrW(&H01FD) & ChrW(&H03B2)

      ' Encode the string using the big-endian byte order.
      ' NOTE: In VB.NET, arrays contain one extra element by default.
      '       The following line creates barrBE with the exact number of elements required.
      Dim barrBE(u32BE.GetByteCount(myStr) - 1) As Byte
      u32BE.GetBytes(myStr, 0, myStr.Length, barrBE, 0)

      ' Encode the string using the little-endian byte order.
      ' NOTE: In VB.NET, arrays contain one extra element by default.
      '       The following line creates barrLE 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, decode eight bytes starting at index 0,
      ' and print out the counts and the resulting bytes.
      Console.Write("BE array with BE encoding : ")
      PrintCountsAndChars(barrBE, 0, 8, u32BE)
      Console.Write("LE array with LE encoding : ")
      PrintCountsAndChars(barrLE, 0, 8, u32LE)

   End Sub


   Public Shared Sub PrintCountsAndChars(bytes() As Byte, index As Integer, count As Integer, 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, index, count)
      Console.Write(" {0,-3}", iCC)

      ' Display the maximum character count.
      Dim iMCC As Integer = enc.GetMaxCharCount(count)
      Console.Write(" {0,-3} :", iMCC)

      ' Decode the bytes.
      Dim chars As Char() = enc.GetChars(bytes, index, count)

      ' The following is an alternative way to decode the bytes:
      ' NOTE: In VB.NET, arrays contain one extra element by default.
      '       The following line creates the array with the exact number of elements required.
      ' Dim chars(iCC - 1) As Char
      ' enc.GetChars( bytes, index, count, chars, 0 )

      ' Display the characters.
      Console.WriteLine(chars)

   End Sub

End Class


'This code produces the following output.  The question marks take the place of characters that cannot be displayed at the console.
'
'BE array with BE encoding : System.Text.UTF32Encoding : 2   6   :za
'LE array with LE encoding : System.Text.UTF32Encoding : 2   6   :za

Uwagi

Encoding.GetChars pobiera znaki z sekwencji bajtów wejściowych. Encoding.GetChars różni się od tego, Decoder.GetChars ponieważ Encoding oczekuje dyskretnych konwersji, podczas gdy Decoder jest przeznaczony dla wielu przechodzi na jednym strumieniu wejściowym.

Jeśli dane do konwersji są dostępne tylko w blokach sekwencyjnych (takich jak dane odczytane ze strumienia) lub jeśli ilość danych jest tak duża, że musi być podzielona na mniejsze bloki, należy użyć Decoder metody lub Encoder podanej odpowiednio przez GetDecoder metodę lub GetEncoder metodę pochodnej.

Uwaga

Ta metoda ma działać na znakach Unicode, a nie na dowolnych danych binarnych, takich jak tablice bajtów. Jeśli musisz zakodować dowolne dane binarne do tekstu, należy użyć protokołu takiego jak uuencode, który jest implementowany przez metody takie jak Convert.ToBase64CharArray.

Metoda GetCharCount określa, ile znaków powoduje dekodowanie sekwencji bajtów, a GetChars metoda wykonuje rzeczywiste dekodowanie. Metoda Encoding.GetChars oczekuje dyskretnych konwersji, w przeciwieństwie do metody, która obsługuje wiele przechodzi w jednym strumieniu Decoder.GetChars wejściowym.

Obsługiwane są kilka wersji GetCharCount i GetChars . Poniżej przedstawiono kilka zagadnień programistycznych dotyczących używania tych metod:

  • Aplikacja może wymagać dekodowania wielu bajtów wejściowych ze strony kodu i przetwarzania bajtów przy użyciu wielu wywołań. W takim przypadku prawdopodobnie trzeba zachować stan między wywołaniami, ponieważ sekwencje bajtów można przerwać podczas przetwarzania w partiach. (Na przykład część sekwencji przesunięcia ISO-2022 może zakończyć jedno GetChars wywołanie i kontynuować na początku następnego GetChars wywołania. Encoding.GetChars Wywoła rezerwę dla tych niekompletnych sekwencji, ale Decoder zapamięta te sekwencje dla następnego wywołania).

  • Jeśli aplikacja obsługuje dane wyjściowe ciągu, zaleca się użycie GetString metody . Ponieważ ta metoda musi sprawdzić długość ciągu i przydzielić bufor, jest nieco wolniejsza, ale wynikowy String typ ma być preferowany.

  • Wersja bajtu umożliwia GetChars(Byte*, Int32, Char*, Int32) szybkie techniki, szczególnie w przypadku wielu wywołań do dużych buforów. Należy jednak pamiętać, że ta wersja metody jest czasami niebezpieczna, ponieważ wskaźniki są wymagane.

  • Jeśli aplikacja musi przekonwertować dużą ilość danych, należy ponownie użyć buforu wyjściowego. W takim przypadku wersja, która obsługuje bufory znaków wyjściowych, GetChars(Byte[], Int32, Int32, Char[], Int32) jest najlepszym wyborem.

  • Rozważ użycie Decoder.Convert metody zamiast GetCharCountmetody . Metoda konwersji konwertuje jak najwięcej danych i zgłasza wyjątek, jeśli bufor wyjściowy jest za mały. W przypadku ciągłego dekodowania strumienia ta metoda jest często najlepszym wyborem.

Zobacz też

Dotyczy

GetChars(ReadOnlySpan<Byte>, Span<Char>)

W przypadku zastąpienia w klasie pochodnej dekoduje wszystkie bajty w określonym zakresie bajtów tylko do odczytu w zakresie znaków.

public:
 virtual int GetChars(ReadOnlySpan<System::Byte> bytes, Span<char> chars);
public virtual int GetChars (ReadOnlySpan<byte> bytes, Span<char> chars);
abstract member GetChars : ReadOnlySpan<byte> * Span<char> -> int
override this.GetChars : ReadOnlySpan<byte> * Span<char> -> int
Public Overridable Function GetChars (bytes As ReadOnlySpan(Of Byte), chars As Span(Of Char)) As Integer

Parametry

bytes
ReadOnlySpan<Byte>

Zakres tylko do odczytu zawierający sekwencję bajtów do dekodowania.

chars
Span<Char>

Znak obejmuje odbieranie zdekodowanych bajtów.

Zwraca

Rzeczywista liczba znaków zapisanych w zakresie wskazanym przez chars parametr .

Uwagi

Encoding.GetChars pobiera znaki z zakresu bajtów wejściowych. Encoding.GetChars różni się od tego, Decoder.GetChars ponieważ Encoding oczekuje dyskretnych konwersji, podczas gdy Decoder jest przeznaczony dla wielu przechodzi na jednym strumieniu wejściowym.

Jeśli dane do konwersji są dostępne tylko w blokach sekwencyjnych (takich jak dane odczytane ze strumienia) lub jeśli ilość danych jest tak duża, że musi być podzielona na mniejsze bloki, należy użyć Decoder metody lub Encoder podanej odpowiednio przez GetDecoder metodę lub GetEncoder metodę pochodnej.

Metoda GetCharCount określa, ile znaków powoduje dekodowanie sekwencji bajtów, a GetChars metoda wykonuje rzeczywiste dekodowanie. Metoda Encoding.GetChars oczekuje dyskretnych konwersji, w przeciwieństwie do metody, która obsługuje wiele przechodzi w jednym strumieniu Decoder.GetChars wejściowym.

Obsługiwane są kilka wersji GetCharCount i GetChars . Poniżej przedstawiono kilka zagadnień programistycznych dotyczących używania tych metod:

  • Aplikacja może wymagać dekodowania wielu bajtów wejściowych ze strony kodu i przetwarzania bajtów przy użyciu wielu wywołań. W takim przypadku prawdopodobnie trzeba zachować stan między wywołaniami, ponieważ sekwencje bajtów można przerwać podczas przetwarzania w partiach. (Na przykład część sekwencji przesunięcia ISO-2022 może zakończyć jedno GetChars wywołanie i kontynuować na początku następnego GetChars wywołania. Encoding.GetChars Wywoła rezerwę dla tych niekompletnych sekwencji, ale Decoder zapamięta te sekwencje dla następnego wywołania).

  • Jeśli aplikacja obsługuje dane wyjściowe ciągu, zaleca się użycie GetString metody . Ponieważ ta metoda musi sprawdzić długość ciągu i przydzielić bufor, jest nieco wolniejsza, ale wynikowy String typ ma być preferowany.

  • Wersja bajtu umożliwia GetChars(Byte*, Int32, Char*, Int32) szybkie techniki, szczególnie w przypadku wielu wywołań do dużych buforów. Należy jednak pamiętać, że ta wersja metody jest czasami niebezpieczna, ponieważ wskaźniki są wymagane.

  • Jeśli aplikacja musi przekonwertować dużą ilość danych, należy ponownie użyć buforu wyjściowego. W takim przypadku wersja, która obsługuje bufory znaków wyjściowych, GetChars(Byte[], Int32, Int32, Char[], Int32) jest najlepszym wyborem.

  • Rozważ użycie Decoder.Convert metody zamiast GetCharCountmetody . Metoda konwersji konwertuje jak najwięcej danych i zgłasza wyjątek, jeśli bufor wyjściowy jest za mały. W przypadku ciągłego dekodowania strumienia ta metoda jest często najlepszym wyborem.

Dotyczy

GetChars(Byte[])

Po przesłonięciu w klasie pochodnej wszystkie bajty w określonej tablicy bajtów są dekodowane w zestawie znaków.

public:
 virtual cli::array <char> ^ GetChars(cli::array <System::Byte> ^ bytes);
public virtual char[] GetChars (byte[] bytes);
abstract member GetChars : byte[] -> char[]
override this.GetChars : byte[] -> char[]
Public Overridable Function GetChars (bytes As Byte()) As Char()

Parametry

bytes
Byte[]

Tablica bajtów zawierająca sekwencję bajtów do dekodowania.

Zwraca

Char[]

Tablica znaków zawierająca wyniki dekodowania określonej sekwencji bajtów.

Wyjątki

bytes to null.

Wystąpił rezerwowy (aby uzyskać więcej informacji, zobacz Kodowanie znaków na platformie .NET)

-I-

DecoderFallback jest ustawiona na DecoderExceptionFallbackwartość .

Przykłady

Poniższy przykład koduje ciąg do tablicy bajtów, a następnie dekoduje bajty do tablicy znaków.

using namespace System;
using namespace System::Text;
void PrintCountsAndChars( array<Byte>^bytes, Encoding^ enc );
int main()
{
   
   // Create two instances of UTF32Encoding: one with little-endian byte order and one with big-endian byte order.
   Encoding^ u32LE = Encoding::GetEncoding( "utf-32" );
   Encoding^ u32BE = Encoding::GetEncoding( "utf-32BE" );
   
   // Use a 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)
   String^ myStr = "za\u0306\u01FD\u03B2";
   
   // Encode the string using the big-endian byte order.
   array<Byte>^barrBE = gcnew array<Byte>(u32BE->GetByteCount( myStr ));
   u32BE->GetBytes( myStr, 0, myStr->Length, barrBE, 0 );
   
   // Encode the string using the little-endian byte order.
   array<Byte>^barrLE = gcnew array<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 );
}

void PrintCountsAndChars( array<Byte>^bytes, Encoding^ enc )
{
   
   // Display the name of the encoding used.
   Console::Write( "{0,-25} :", enc );
   
   // 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.
   array<Char>^chars = enc->GetChars( bytes );
   Console::WriteLine( chars );
}

/* 
This code produces the following output.  The question marks take the place of characters that cannot be displayed at the console.

BE array with BE encoding : System.Text.UTF32Encoding : 5   12  :zăǽβ
LE array with LE encoding : System.Text.UTF32Encoding : 5   12  :zăǽβ

*/
using System;
using System.Text;

public class SamplesEncoding  {

   public static void Main()  {

      // Create two instances of UTF32Encoding: one with little-endian byte order and one with big-endian byte order.
      Encoding u32LE = Encoding.GetEncoding( "utf-32" );
      Encoding u32BE = Encoding.GetEncoding( "utf-32BE" );

      // Use a 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)
      String myStr = "za\u0306\u01FD\u03B2";

      // Encode the string using the big-endian byte order.
      byte[] barrBE = new byte[u32BE.GetByteCount( myStr )];
      u32BE.GetBytes( myStr, 0, myStr.Length, barrBE, 0 );

      // Encode the string using 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 );
   }

   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 = enc.GetChars( bytes );
      Console.WriteLine( chars );
   }
}


/* 
This code produces the following output.  The question marks take the place of characters that cannot be displayed at the console.

BE array with BE encoding : System.Text.UTF32Encoding : 5   12  :zăǽβ
LE array with LE encoding : System.Text.UTF32Encoding : 5   12  :zăǽβ

*/
Imports System.Text

Public Class SamplesEncoding   

   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 Encoding = Encoding.GetEncoding("utf-32")
      Dim u32BE As Encoding = Encoding.GetEncoding("utf-32BE")

      ' Use a 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)
      Dim myStr As String = "za" & ChrW(&H0306) & ChrW(&H01FD) & ChrW(&H03B2) 

      ' Encode the string using the big-endian byte order.
      ' NOTE: In VB.NET, arrays contain one extra element by default.
      '       The following line creates the array with the exact number of elements required.
      Dim barrBE(u32BE.GetByteCount(myStr) - 1) As Byte
      u32BE.GetBytes(myStr, 0, myStr.Length, barrBE, 0)

      ' Encode the string using the little-endian byte order.
      ' NOTE: In VB.NET, arrays contain one extra element by default.
      '       The following line creates the 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)

   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 As Char() = enc.GetChars(bytes)
      Console.WriteLine(chars)

   End Sub

End Class


'This code produces the following output.  The question marks take the place of characters that cannot be displayed at the console.
'
'BE array with BE encoding : System.Text.UTF32Encoding : 5   12  :zăǽβ
'LE array with LE encoding : System.Text.UTF32Encoding : 5   12  :zăǽβ

Uwagi

Encoding.GetChars pobiera znaki z sekwencji bajtów wejściowych. Encoding.GetChars różni się od tego, Decoder.GetChars ponieważ Encoding oczekuje dyskretnych konwersji, podczas gdy Decoder jest przeznaczony dla wielu przechodzi na jednym strumieniu wejściowym.

Jeśli dane do konwersji są dostępne tylko w blokach sekwencyjnych (takich jak dane odczytane ze strumienia) lub jeśli ilość danych jest tak duża, że musi być podzielona na mniejsze bloki, należy użyć Decoder metody lub Encoder podanej odpowiednio przez GetDecoder metodę lub GetEncoder metodę pochodnej.

Uwaga

Ta metoda ma działać na znakach Unicode, a nie na dowolnych danych binarnych, takich jak tablice bajtów. Jeśli musisz zakodować dowolne dane binarne do tekstu, należy użyć protokołu takiego jak uuencode, który jest implementowany przez metody takie jak Convert.ToBase64CharArray.

Metoda GetCharCount określa, ile znaków powoduje dekodowanie sekwencji bajtów, a GetChars metoda wykonuje rzeczywiste dekodowanie. Metoda Encoding.GetChars oczekuje dyskretnych konwersji, w przeciwieństwie do metody, która obsługuje wiele przechodzi w jednym strumieniu Decoder.GetChars wejściowym.

Obsługiwane są kilka wersji GetCharCount i GetChars . Poniżej przedstawiono kilka zagadnień programistycznych dotyczących używania tych metod:

  • Aplikacja może wymagać dekodowania wielu bajtów wejściowych ze strony kodu i przetwarzania bajtów przy użyciu wielu wywołań. W takim przypadku prawdopodobnie trzeba zachować stan między wywołaniami, ponieważ sekwencje bajtów można przerwać podczas przetwarzania w partiach. (Na przykład część sekwencji przesunięcia ISO-2022 może zakończyć jedno GetChars wywołanie i kontynuować na początku następnego GetChars wywołania. Encoding.GetChars Wywoła rezerwę dla tych niekompletnych sekwencji, ale Decoder zapamięta te sekwencje dla następnego wywołania).

  • Jeśli aplikacja obsługuje dane wyjściowe ciągu, zaleca się użycie GetString metody . Ponieważ ta metoda musi sprawdzić długość ciągu i przydzielić bufor, jest nieco wolniejsza, ale wynikowy String typ ma być preferowany.

  • Wersja bajtu umożliwia GetChars(Byte*, Int32, Char*, Int32) szybkie techniki, szczególnie w przypadku wielu wywołań do dużych buforów. Należy jednak pamiętać, że ta wersja metody jest czasami niebezpieczna, ponieważ wskaźniki są wymagane.

  • Jeśli aplikacja musi przekonwertować dużą ilość danych, należy ponownie użyć buforu wyjściowego. W takim przypadku wersja, która obsługuje bufory znaków wyjściowych, GetChars(Byte[], Int32, Int32, Char[], Int32) jest najlepszym wyborem.

  • Rozważ użycie Decoder.Convert metody zamiast GetCharCountmetody . Metoda konwersji konwertuje jak najwięcej danych i zgłasza wyjątek, jeśli bufor wyjściowy jest za mały. W przypadku ciągłego dekodowania strumienia ta metoda jest często najlepszym wyborem.

Zobacz też

Dotyczy