UTF8Encoding.GetEncoder 메서드

정의

유니코드 문자 시퀀스를 UTF-8로 인코딩된 바이트 시퀀스로 변환하는 인코더를 가져옵니다.

public:
 override System::Text::Encoder ^ GetEncoder();
public override System.Text.Encoder GetEncoder();
override this.GetEncoder : unit -> System.Text.Encoder
Public Overrides Function GetEncoder () As Encoder

반품

Encoder 유니코드 문자 시퀀스를 UTF-8로 인코딩된 바이트 시퀀스로 변환하는 A입니다.

예제

다음 예제에서는 메서드를 사용하여 GetEncoder 인코더를 가져와 문자 시퀀스를 UTF-8로 인코딩된 바이트 시퀀스로 변환합니다.

using System;
using System.Text;

class UTF8EncodingExample {
    public static void Main() {
        Char[] chars = new Char[] {'a', 'b', 'c', '\u0300', '\ua0a0'};
        Byte[] bytes;

        Encoder utf8Encoder = Encoding.UTF8.GetEncoder();

        int byteCount = utf8Encoder.GetByteCount(chars, 2, 3, true);
        bytes = new Byte[byteCount];
        int bytesEncodedCount = utf8Encoder.GetBytes(chars, 2, 3, bytes, 0, true);

        Console.WriteLine(
            "{0} bytes used to encode characters.", bytesEncodedCount
        );

        Console.Write("Encoded bytes: ");
        foreach (Byte b in bytes) {
            Console.Write("[{0}]", b);
        }
        Console.WriteLine();
    }
}
Imports System.Text
Imports Microsoft.VisualBasic.Strings

Class UTF8EncodingExample
    
    Public Shared Sub Main()
        'Characters:
        ' ChrW(97) = a
        ' ChrW(98) = b
        ' ChrW(99) = c
        ' ChrW(768) = `
        ' ChrW(41120) = valid unicode code point, but not a character
        Dim chars() As Char = {ChrW(97), ChrW(98), ChrW(99), ChrW(768), ChrW(41120)}
        Dim bytes() As Byte
        
        Dim utf8Encoder As Encoder = Encoding.UTF8.GetEncoder()
        
        Dim byteCount As Integer = utf8Encoder.GetByteCount(chars, 2, 3, True)
        bytes = New Byte(byteCount - 1) {}
        Dim bytesEncodedCount As Integer = utf8Encoder.GetBytes( _
            chars, 2, 3, bytes, 0, True _
        )
        
        Console.WriteLine("{0} bytes used to encode characters.", bytesEncodedCount)
        
        Console.Write("Encoded bytes: ")
        Dim b As Byte
        For Each b In  bytes
            Console.Write("[{0}]", b)
        Next b
        Console.WriteLine()
    End Sub
End Class

설명

이 메서드는 Encoder.GetBytes 순차적 문자 블록을 메서드와 비슷한 방식으로 순차적 바이트 블록으로 GetBytes 변환합니다. 그러나 Encoder 호출 간에 상태 정보를 유지 관리하므로 블록에 걸쳐 있는 문자 시퀀스를 올바르게 인코딩할 수 있습니다. Encoder 또한 데이터 블록의 끝에 후행 문자를 유지하고 다음 인코딩 작업에서 후행 문자를 사용합니다. 예를 들어 데이터 블록은 일치하지 않는 높은 서로게이트로 끝날 수 있으며 일치하는 하위 서로게이트는 다음 데이터 블록에 있을 수 있습니다. 따라서 GetDecoderGetEncoder 이러한 작업은 전체 데이터 스트림 대신 데이터 블록을 처리하는 경우가 많기 때문에 네트워크 전송 및 파일 작업에 유용합니다.

오류 검색을 사용하도록 설정 throwOnInvalidCharacters 하면 생성자의 매개 변수가 설정되고 이 메서드에서 Encoder 반환된 오류 검색도 사용하도록 설정true됩니다. 오류 검색을 사용하도록 설정하고 잘못된 시퀀스를 발견하면 인코더의 상태가 정의되지 않고 처리가 중지되어야 합니다.

적용 대상

추가 정보