UTF8Encoding.GetEncoder 方法

定义

获取将 Unicode 字符序列转换为 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 Unicode 字符序列转换为 UTF-8 编码的字节序列。

示例

以下示例使用 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 保留数据块末尾的尾随字符,并在下一个编码操作中使用尾随字符。 例如,数据块可能以不匹配的高代理项结尾,匹配的低代理项可能位于下一个数据块中。 因此, GetDecoder 对于 GetEncoder 网络传输和文件操作非常有用,因为这些操作通常处理数据块而不是完整的数据流。

如果启用了错误检测,即 throwOnInvalidCharacters 构造函数的参数设置为 true,则此方法返回的错误 Encoder 检测也会启用。 如果启用错误检测并且遇到无效序列,则编码器的状态未定义且处理必须停止。

适用于

另请参阅