UnicodeEncoding.GetEncoder Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Получает кодировщик, который преобразует последовательность символов Юникода в последовательность байтов в кодировке UTF-16.
public:
override System::Text::Encoder ^ GetEncoder();
public override System.Text.Encoder GetEncoder();
[System.Runtime.InteropServices.ComVisible(false)]
public override System.Text.Encoder GetEncoder();
override this.GetEncoder : unit -> System.Text.Encoder
[<System.Runtime.InteropServices.ComVisible(false)>]
override this.GetEncoder : unit -> System.Text.Encoder
Public Overrides Function GetEncoder () As Encoder
Возвращаемое значение
Encoder Объект, который преобразует последовательность символов Юникода в последовательность байтов в кодировке UTF-16.
- Атрибуты
Примеры
В следующем примере используется кодировщик и декодировщик для кодирования строки в массив байтов, а затем декодирование байтов в массив символов.
using System;
using System.Text;
public class SamplesUnicodeEncoding {
public static void Main() {
// Get an encoder and a decoder from UnicodeEncoding.
UnicodeEncoding u16 = new UnicodeEncoding( false, true, true );
Encoder myEnc = u16.GetEncoder();
Decoder myDec = u16.GetDecoder();
// The characters to encode:
// 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)
char[] myChars = new char[5] { 'z', 'a', '\u0306', '\u01FD', '\u03B2' };
Console.Write( "The original characters : " );
Console.WriteLine( myChars );
// Encode the character array.
int iBC = myEnc.GetByteCount( myChars, 0, myChars.Length, true );
byte[] myBytes = new byte[iBC];
myEnc.GetBytes( myChars, 0, myChars.Length, myBytes, 0, true );
// Print the resulting bytes.
Console.Write( "Using the encoder : " );
for ( int i = 0; i < myBytes.Length; i++ )
Console.Write( "{0:X2} ", myBytes[i] );
Console.WriteLine();
// Decode the byte array back into an array of characters.
int iCC = myDec.GetCharCount( myBytes, 0, myBytes.Length, true );
char[] myDecodedChars = new char[iCC];
myDec.GetChars( myBytes, 0, myBytes.Length, myDecodedChars, 0, true );
// Print the resulting characters.
Console.Write( "Using the decoder : " );
Console.WriteLine( myDecodedChars );
}
}
/*
This code produces the following output. The question marks take the place of characters that cannot be displayed at the console.
The original characters : za??ß
Using the encoder : 7A 00 61 00 06 03 FD 01 B2 03
Using the decoder : za??ß
*/
Imports System.Text
Public Class SamplesUnicodeEncoding
Public Shared Sub Main()
' Get an encoder and a decoder from UnicodeEncoding.
Dim u16 As New UnicodeEncoding(False, True, True)
Dim myEnc As Encoder = u16.GetEncoder()
Dim myDec As Decoder = u16.GetDecoder()
' The characters to encode:
' 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 myChars() As Char = {"z"c, "a"c, ChrW(&H0306), ChrW(&H01FD), ChrW(&H03B2)}
Console.Write("The original characters : ")
Console.WriteLine(myChars)
' Encode the character array.
Dim iBC As Integer = myEnc.GetByteCount(myChars, 0, myChars.Length, True)
' 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 myBytes(iBC - 1) As Byte
myEnc.GetBytes(myChars, 0, myChars.Length, myBytes, 0, True)
' Print the resulting bytes.
Console.Write("Using the encoder : ")
Dim i As Integer
For i = 0 To myBytes.Length - 1
Console.Write("{0:X2} ", myBytes(i))
Next i
Console.WriteLine()
' Decode the byte array back into an array of characters.
Dim iCC As Integer = myDec.GetCharCount(myBytes, 0, myBytes.Length, True)
' 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 myDecodedChars(iCC - 1) As Char
myDec.GetChars(myBytes, 0, myBytes.Length, myDecodedChars, 0, True)
' Print the resulting characters.
Console.Write("Using the decoder : ")
Console.WriteLine(myDecodedChars)
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.
'
'The original characters : za??ß
'Using the encoder : 7A 00 61 00 06 03 FD 01 B2 03
'Using the decoder : za??ß
Комментарии
Метод Encoder.GetBytes преобразует последовательные блоки символов в последовательные блоки байтов таким образом, как GetBytes и метод этого класса. Encoder Однако объект сохраняет сведения о состоянии между вызовами, чтобы он смог правильно кодировать последовательности символов, охватывающие блоки. Объект Encoder также сохраняет конечные символы в конце блоков данных и использует конечные символы в следующей операции кодирования. Например, блок данных может завершиться несоответствующим высоким суррогатом, и соответствующий низкий суррогат может находиться в следующем блоке данных. Таким образом, GetDecoder и GetEncoder они полезны для сетевых операций передачи и файлов, так как эти операции часто имеют дело с блоками данных вместо полного потока данных.
Если включено обнаружение ошибок, то throwOnInvalidBytes есть параметр конструктора имеет trueзначение, обнаружение ошибок также включено в объекте Encoder , возвращаемом этим методом. Если обнаружена ошибка и обнаружена недопустимая последовательность, состояние кодировщика не определено и обработка должна остановиться.