Encoding.GetPreamble 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
當在派生類別中覆寫時,會回傳一串位元組,指定所使用的編碼方式。
public:
virtual cli::array <System::Byte> ^ GetPreamble();
public virtual byte[] GetPreamble();
abstract member GetPreamble : unit -> byte[]
override this.GetPreamble : unit -> byte[]
Public Overridable Function GetPreamble () As Byte()
傳回
一個位元組陣列,包含一串位元組,指定所使用的編碼方式。
-或-
若不需前言,則為長度為零的位元組陣列。
範例
以下範例根據前言決定編碼的位元組順序。
using System;
using System.Text;
namespace GetPreambleExample
{
class GetPreambleExampleClass
{
static void Main()
{
Encoding unicode = Encoding.Unicode;
// Get the preamble for the Unicode encoder.
// In this case the preamble contains the byte order mark (BOM).
byte[] preamble = unicode.GetPreamble();
// Make sure a preamble was returned
// and is large enough to contain a BOM.
if(preamble.Length >= 2)
{
if(preamble[0] == 0xFE && preamble[1] == 0xFF)
{
Console.WriteLine("The Unicode encoder is encoding in big-endian order.");
}
else if(preamble[0] == 0xFF && preamble[1] == 0xFE)
{
Console.WriteLine("The Unicode encoder is encoding in little-endian order.");
}
}
}
}
}
/*
This code produces the following output.
The Unicode encoder is encoding in little-endian order.
*/
Imports System.Text
Namespace GetPreambleExample
Class GetPreambleExampleClass
Shared Sub Main()
Dim [unicode] As Encoding = Encoding.Unicode
' Get the preamble for the Unicode encoder.
' In this case the preamble contains the byte order mark (BOM).
Dim preamble As Byte() = [unicode].GetPreamble()
' Make sure a preamble was returned
' and is large enough to contain a BOM.
If preamble.Length >= 2 Then
If preamble(0) = &HFE And preamble(1) = &HFF Then
Console.WriteLine("The Unicode encoder is encoding in big-endian order.")
Else
If preamble(0) = &HFF And preamble(1) = &HFE Then
Console.WriteLine("The Unicode encoder is encoding in little-endian order.")
End If
End If
End If
End Sub
End Class
End Namespace
'This code produces the following output.
'
'The Unicode encoder is encoding in little-endian order.
'
備註
物件可 Encoding 選擇性地提供一個前導碼,這是一個位元組陣列,可以作為編碼過程產生的位元組序列前綴。 如果前導碼包含位元組順序標記(Unicode 中代碼點 U+FEFF),它有助於解碼器判斷位元組順序及轉換格式(UTF)。
Unicode 位元組序標記(BOM)序列化如下(十六進位):
UTF-8:EF BB BF
UTF-16 大端序位元組序:FE FF
UTF-16 小端序位元組序:FF FE
UTF-32 大端序位元組序:00 00 FE FF
UTF-32 小端序位元組序:FF FE 00 00
你應該使用物料清單,因為它幾乎能確定辨識那些已經失去物件參考的 Encoding 檔案編碼,例如未標記或錯誤標籤的網頁資料,或是企業沒有國際事務或其他資料時儲存的隨機文字檔。 通常只要資料被一致且正確地標註,最好是 UTF-8 或 UTF-16,使用者問題就能避免。
對於提供編碼類型的標準,BOM 在某種程度上是多餘的。 不過,它也能幫助伺服器傳送正確的編碼標頭。 或者,若編碼遺失,也可以作為備援。
使用物料清單(BOM)有一些缺點。 例如,如何限制使用 BOM 的資料庫欄位可能很困難。 檔案串接也可能成為問題,例如當檔案合併時,導致不必要的字元出現在資料中間。 儘管存在少數缺點,仍強烈建議使用物料清單(BOM)。
如需位元組順序和位元組順序標記的詳細資訊,請參閱 Unicode 首頁上的 Unicode 標準。
注意事項
為了確保編碼後的位元組被正確解碼,你應該在已編碼的位元組前加上前言。 然而,大多數編碼並未提供前言。 為了確保編碼的位元組被正確解碼,你應該使用Unicode編碼,也就是 UTF8Encoding、 、 UnicodeEncoding或 UTF32Encoding,並附上前言。