UTF8Encoding.GetEncoder 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
取得一個編碼器,可將一串 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 A 將一連串 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 方法相似。 然而,a Encoder 會維護呼叫間的狀態資訊,以便正確編碼跨區塊的字元序列。 它 Encoder 也會保留資料區塊末尾的尾部字元,並在下一次編碼操作中使用這些尾部字元。 例如,一個資料區塊可能以一個未匹配的高代體結尾,而匹配的低代體可能在下一個資料區塊中。 因此, GetDecoder 和 GetEncoder 對於網路傳輸和檔案操作非常有用,因為這些操作通常處理的是資料區塊,而非完整的資料流。
若啟用錯誤偵測,也就是 throwOnInvalidCharacters 建構子參數設為 true,錯誤偵測也會在此方法返回的中 Encoder 啟用。 若啟用錯誤偵測且遇到無效序列,編碼器狀態未定義,處理必須停止。