UTF8Encoding.GetDecoder 方法

定義

取得一個解碼器,能將 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 方式類似於此類別的方法。 然而,a Decoder 會維持呼叫間的狀態資訊,以便正確解碼跨區塊的位元組序列。 同時 Decoder 會保留資料區塊末尾的尾部位元組,並在下一次解碼操作中使用這些尾部位元組。 因此, GetDecoderGetEncoder 對於網路傳輸和檔案操作非常有用,因為這些操作通常處理的是資料區塊,而非完整的資料流。

若啟用錯誤偵測,也就是 throwOnInvalidCharacters 建構子參數設為 true,錯誤偵測也會在此方法返回的中 Decoder 啟用。 若啟用錯誤偵測且遇到無效序列,解碼器的狀態為未定義,處理必須停止。

適用於

另請參閱