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
应使用 BOM,因为它为文件提供几乎确定的编码,这些编码在其他情况下丢失了对 Encoding 对象的引用,例如,当企业没有国际问题或其他数据时存储的未标记或不当标记的 Web 数据或随机文本文件。 如果数据一致且正确标记,最好在 UTF-8 或 UTF-16 中避免用户问题。
对于提供编码类型的标准,BOM 有点冗余。 但是,它可用于帮助服务器发送正确的编码标头。 或者,如果编码丢失,则可以将其用作回退。
使用 BOM 有一些缺点。 例如,了解如何限制使用 BOM 的数据库字段可能很困难。 文件串联也可能是个问题,例如,当文件以这样一种方式合并时,不必要的字符最终会出现在数据中间。 但是,尽管存在少数缺点,但强烈建议使用 BOM。
有关字节顺序和字节顺序标记的详细信息,请参阅 Unicode 主页上的 Unicode 标准版。
Caution
为了确保正确解码编码的字节,应为编码的字节加上前缀。 但是,大多数编码不提供前言。 若要确保正确解码编码的字节,应使用 Unicode 编码(即UTF8EncodingUnicodeEncoding、或UTF32Encoding具有前言)。