UTF8Encoding.GetDecoder 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
获取将 UTF-8 编码的字节序列转换为 Unicode 字符序列的解码器。
public:
override System::Text::Decoder ^ GetDecoder();
public override System.Text.Decoder GetDecoder();
override this.GetDecoder : unit -> System.Text.Decoder
Public Overrides Function GetDecoder () As Decoder
返回
将 UTF-8 编码的字节序列转换为 Unicode 字符序列的解码器。
示例
以下示例使用 GetDecoder 该方法获取 UTF-8 解码器。 解码器将字节序列转换为字符序列。
using System;
using System.Text;
class UTF8EncodingExample {
public static void Main() {
Char[] chars;
Byte[] bytes = new Byte[] {
99, 204, 128, 234, 130, 160
};
Decoder utf8Decoder = Encoding.UTF8.GetDecoder();
int charCount = utf8Decoder.GetCharCount(bytes, 0, bytes.Length);
chars = new Char[charCount];
int charsDecodedCount = utf8Decoder.GetChars(bytes, 0, bytes.Length, chars, 0);
Console.WriteLine(
"{0} characters used to decode bytes.", charsDecodedCount
);
Console.Write("Decoded chars: ");
foreach (Char c in chars) {
Console.Write("[{0}]", c);
}
Console.WriteLine();
}
}
Imports System.Text
Class UTF8EncodingExample
Public Shared Sub Main()
Dim chars() As Char
Dim bytes() As Byte = {99, 204, 128, 234, 130, 160}
Dim utf8Decoder As Decoder = Encoding.UTF8.GetDecoder()
Dim charCount As Integer = utf8Decoder.GetCharCount(bytes, 0, bytes.Length)
chars = New Char(charCount - 1) {}
Dim charsDecodedCount As Integer = utf8Decoder.GetChars( _
bytes, 0, bytes.Length, chars, 0 _
)
Console.WriteLine("{0} characters used to decode bytes.", charsDecodedCount)
Console.Write("Decoded chars: ")
Dim c As Char
For Each c In chars
Console.Write("[{0}]", c)
Next c
Console.WriteLine()
End Sub
End Class
注解
该方法 Decoder.GetChars 以类似于 GetChars 此类的方法将连续字节块转换为顺序字符块。 但是,在 Decoder 调用之间维护状态信息,以便它可以正确解码跨块的字节序列。 它还 Decoder 保留数据块末尾的尾随字节,并在下一个解码操作中使用尾随字节。 因此, GetDecoder 对于 GetEncoder 网络传输和文件操作非常有用,因为这些操作通常处理数据块而不是完整的数据流。
如果启用了错误检测,即 throwOnInvalidCharacters 构造函数的参数设置为 true,则此方法返回的错误 Decoder 检测也会启用。 如果启用错误检测并且遇到无效序列,解码器的状态是未定义的,并且处理必须停止。