Encoder.GetBytes 方法

定义

在派生类中重写时,将一组字符编码为一个字节序列。When overridden in a derived class, encodes a set of characters into a sequence of bytes.

重载

GetBytes(ReadOnlySpan<Char>, Span<Byte>, Boolean)
GetBytes(Char*, Int32, Byte*, Int32, Boolean)

在派生类中重写时,将一组字符(从指定的字符指针处开始)和内部缓冲区中的任何字符编码为从指定字节指针开始存储的字节序列。When overridden in a derived class, encodes a set of characters starting at the specified character pointer and any characters in the internal buffer into a sequence of bytes that are stored starting at the specified byte pointer. 一个参数指示转换后是否清除编码器的内部状态。A parameter indicates whether to clear the internal state of the encoder after the conversion.

GetBytes(Char[], Int32, Int32, Byte[], Int32, Boolean)

在派生类中重写时,将指定字符数组中的一组字符和内部缓冲区中的任何字符编码到指定的字节数组中。When overridden in a derived class, encodes a set of characters from the specified character array and any characters in the internal buffer into the specified byte array. 一个参数指示转换后是否清除编码器的内部状态。A parameter indicates whether to clear the internal state of the encoder after the conversion.

GetBytes(ReadOnlySpan<Char>, Span<Byte>, Boolean)

public:
 virtual int GetBytes(ReadOnlySpan<char> chars, Span<System::Byte> bytes, bool flush);
public virtual int GetBytes (ReadOnlySpan<char> chars, Span<byte> bytes, bool flush);
abstract member GetBytes : ReadOnlySpan<char> * Span<byte> * bool -> int
override this.GetBytes : ReadOnlySpan<char> * Span<byte> * bool -> int
Public Overridable Function GetBytes (chars As ReadOnlySpan(Of Char), bytes As Span(Of Byte), flush As Boolean) As Integer

参数

bytes
Span<Byte>
flush
Boolean

返回

GetBytes(Char*, Int32, Byte*, Int32, Boolean)

重要

此 API 不符合 CLS。

在派生类中重写时,将一组字符(从指定的字符指针处开始)和内部缓冲区中的任何字符编码为从指定字节指针开始存储的字节序列。When overridden in a derived class, encodes a set of characters starting at the specified character pointer and any characters in the internal buffer into a sequence of bytes that are stored starting at the specified byte pointer. 一个参数指示转换后是否清除编码器的内部状态。A parameter indicates whether to clear the internal state of the encoder after the conversion.

public:
 virtual int GetBytes(char* chars, int charCount, System::Byte* bytes, int byteCount, bool flush);
[System.CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
[System.Security.SecurityCritical]
public virtual int GetBytes (char* chars, int charCount, byte* bytes, int byteCount, bool flush);
abstract member GetBytes : nativeptr<char> * int * nativeptr<byte> * int * bool -> int
override this.GetBytes : nativeptr<char> * int * nativeptr<byte> * int * bool -> int

参数

chars
Char*

指向第一个要编码的字符的指针。A pointer to the first character to encode.

charCount
Int32

要编码的字符的数目。The number of characters to encode.

bytes
Byte*

一个指针,指向开始写入所产生的字节序列的位置。A pointer to the location at which to start writing the resulting sequence of bytes.

byteCount
Int32

最多写入的字节数。The maximum number of bytes to write.

flush
Boolean

如果要在转换后清除编码器的内部状态,则为 true;否则为 falsetrue to clear the internal state of the encoder after the conversion; otherwise, false.

返回

在由 bytes 参数指示的位置处写入的实际字节数。The actual number of bytes written at the location indicated by the bytes parameter.

属性

异常

charsnull (Nothing)。chars is null (Nothing).

-or- bytesnull (Nothing)。bytes is null (Nothing).

charCountbyteCount 小于零。charCount or byteCount is less than zero.

byteCount 少于所产生的字节数。byteCount is less than the resulting number of bytes.

发生了回退(有关更完整的说明,请参阅 .NET Framework 中的字符编码A fallback occurred (see Character Encoding in the .NET Framework for fuller explanation) -和--and- Fallback 设置为 EncoderExceptionFallbackFallback is set to EncoderExceptionFallback.

注解

请记住, Encoder对象会在GetBytes调用之间保存状态。Remember that the Encoder object saves state between calls to GetBytes. 当应用程序使用数据流完成时,它应将flush参数设置为true ,并GetBytes在最后调用中将参数设置为,以确保刷新状态信息并正确终止已编码的字节。When the application is done with a stream of data, it should set the flush parameter to true in the last call to GetBytes to make sure that the state information is flushed and that the encoded bytes are properly terminated. 通过此设置,编码器将忽略数据块末尾的无效字节,如不匹配的代理项或不完整的组合序列,并清除内部缓冲区。With this setting, the encoder ignores invalid bytes at the end of the data block, such as unmatched surrogates or incomplete combining sequences, and clears the internal buffer.

若要计算存储所生成的GetBytes字符所需的确切缓冲区大小,应用程序应GetByteCount使用。To calculate the exact buffer size that GetBytes requires to store the resulting characters, the application should use GetByteCount.

如果GetBytesflush设置为false的情况下调用,编码器会将结尾字节存储在内部缓冲区中的数据块的末尾,并在下一个编码操作中使用它们。If GetBytes is called with flush set to false, the encoder stores trailing bytes at the end of the data block in an internal buffer and uses them in the next encoding operation. 应用程序应在GetByteCount对同一块调用GetBytes之前立即调用数据块,以便在计算中包括前一块中的任何尾随字符。The application should call GetByteCount on a block of data immediately before calling GetBytes on the same block, so that any trailing characters from the previous block are included in the calculation.

如果你的应用程序要转换输入流的多个段,请考虑Convert使用方法。If your application is to convert many segments of an input stream, consider using the Convert method. GetBytes如果输出缓冲区不够大,将会引发异常,但Convert会尽可能多地填入空间,并返回读取的字符和写入的字节数。GetBytes will throw an exception if the output buffer isn't large enough, but Convert will fill as much space as possible and return the chars read and bytes written. 有关更多Encoding.GetBytes注释,另请参阅主题。Also see the Encoding.GetBytes topic for more comments.

安全性

SecurityCriticalAttribute
需要对直接调用方的完全信任。Requires full trust for the immediate caller. 部分受信任的或透明的代码不能使用此成员。This member cannot be used by partially trusted or transparent code.

另请参阅

GetBytes(Char[], Int32, Int32, Byte[], Int32, Boolean)

在派生类中重写时,将指定字符数组中的一组字符和内部缓冲区中的任何字符编码到指定的字节数组中。When overridden in a derived class, encodes a set of characters from the specified character array and any characters in the internal buffer into the specified byte array. 一个参数指示转换后是否清除编码器的内部状态。A parameter indicates whether to clear the internal state of the encoder after the conversion.

public:
 abstract int GetBytes(cli::array <char> ^ chars, int charIndex, int charCount, cli::array <System::Byte> ^ bytes, int byteIndex, bool flush);
public abstract int GetBytes (char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush);
abstract member GetBytes : char[] * int * int * byte[] * int * bool -> int
Public MustOverride Function GetBytes (chars As Char(), charIndex As Integer, charCount As Integer, bytes As Byte(), byteIndex As Integer, flush As Boolean) As Integer

参数

chars
Char[]

包含要编码的字符集的字符数组。The character array containing the set of characters to encode.

charIndex
Int32

第一个要编码的字符的索引。The index of the first character to encode.

charCount
Int32

要编码的字符的数目。The number of characters to encode.

bytes
Byte[]

要包含所产生的字节序列的字节数组。The byte array to contain the resulting sequence of bytes.

byteIndex
Int32

要开始写入所产生的字节序列的索引位置。The index at which to start writing the resulting sequence of bytes.

flush
Boolean

如果要在转换后清除编码器的内部状态,则为 true;否则为 falsetrue to clear the internal state of the encoder after the conversion; otherwise, false.

返回

写入 bytes 的实际字节数。The actual number of bytes written into bytes.

异常

charsnull (Nothing)。chars is null (Nothing).

- 或 --or- bytesnull (Nothing)。bytes is null (Nothing).

charIndexcharCountbyteIndex 小于零。charIndex or charCount or byteIndex is less than zero.

-or- charIndexcharCount 不表示 chars中的有效范围。charIndex and charCount do not denote a valid range in chars.

-or- byteIndex 不是 bytes 中的有效索引。byteIndex is not a valid index in bytes.

bytes 中从 byteIndex 到数组结尾没有足够的容量来容纳所产生的字节。bytes does not have enough capacity from byteIndex to the end of the array to accommodate the resulting bytes.

发生了回退(有关更完整的说明,请参阅 .NET Framework 中的字符编码A fallback occurred (see Character Encoding in the .NET Framework for fuller explanation) -和--and- Fallback 设置为 EncoderExceptionFallbackFallback is set to EncoderExceptionFallback.

示例

下面的示例演示如何对字符数组中的一系列元素进行编码,并将已编码的字节存储在字节数组中的一系列元素中。The following example demonstrates how to encode a range of elements from a character array and store the encoded bytes in a range of elements in a byte array. 方法用于确定GetBytes所需的数组大小。 GetByteCountThe GetByteCount method is used to determine the size of the array required by GetBytes.

using namespace System;
using namespace System::Text;
using namespace System::Collections;
int main()
{
   array<Byte>^bytes;
   
   // Unicode characters.
   
   // Pi
   // Sigma
   array<Char>^chars = {L'\u03a0',L'\u03a3',L'\u03a6',L'\u03a9'};
   Encoder^ uniEncoder = Encoding::Unicode->GetEncoder();
   int byteCount = uniEncoder->GetByteCount( chars, 0, chars->Length, true );
   bytes = gcnew array<Byte>(byteCount);
   int bytesEncodedCount = uniEncoder->GetBytes( chars, 0, chars->Length, bytes, 0, true );
   Console::WriteLine( "{0} bytes used to encode characters.", bytesEncodedCount );
   Console::Write( "Encoded bytes: " );
   IEnumerator^ myEnum = bytes->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Byte b = safe_cast<Byte>(myEnum->Current);
      Console::Write( "[{0}]", b );
   }

   Console::WriteLine();
}

/* This code example produces the following output.

8 bytes used to encode characters.
Encoded bytes: [160][3][163][3][166][3][169][3]

*/

using System;
using System.Text;

class EncoderExample {
    public static void Main() {
        Byte[] bytes;
        // Unicode characters.
        Char[] chars = new Char[] {
            '\u0023', // #
            '\u0025', // %
            '\u03a0', // Pi
            '\u03a3'  // Sigma
        };
        
        Encoder uniEncoder = Encoding.Unicode.GetEncoder();
        
        int byteCount = uniEncoder.GetByteCount(chars, 0, chars.Length, true);
        bytes = new Byte[byteCount];
        int bytesEncodedCount = uniEncoder.GetBytes(chars, 0, chars.Length, 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();
    }
}

/* This code example produces the following output.

8 bytes used to encode characters.
Encoded bytes: [35][0][37][0][160][3][163][3]

*/
Imports System.Text
Imports Microsoft.VisualBasic.Strings

Class EncoderExample
    
    Public Shared Sub Main()
        Dim bytes() As Byte
        ' Unicode characters.
        ' ChrW(35)  = #
        ' ChrW(37)  = %
        ' ChrW(928) = Pi
        ' ChrW(931) = Sigma
        Dim chars() As Char = {ChrW(35), ChrW(37), ChrW(928), ChrW(931)}
        
        Dim uniEncoder As Encoder = Encoding.Unicode.GetEncoder()
        
        Dim byteCount As Integer = _
            uniEncoder.GetByteCount(chars, 0, chars.Length, True)
        bytes = New Byte(byteCount - 1) {}
        Dim bytesEncodedCount As Integer = _
            uniEncoder.GetBytes(chars, 0, chars.Length, 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

'This code example produces the following output.
'8 bytes used to encode characters.
'Encoded bytes: [35][0][37][0][160][3][163][3]
'

注解

请记住, Encoder对象会在GetBytes调用之间保存状态。Remember that the Encoder object saves state between calls to GetBytes. 当应用程序使用数据流完成时,它应将flush参数设置为true ,并GetBytes在最后调用中将参数设置为,以确保刷新状态信息并正确终止已编码的字节。When the application is done with a stream of data, it should set the flush parameter to true in the last call to GetBytes to make sure that the state information is flushed and that the encoded bytes are properly terminated. 通过此设置,编码器将忽略数据块末尾的无效字节,如不匹配的代理项或不完整的组合序列,并清除内部缓冲区。With this setting, the encoder ignores invalid bytes at the end of the data block, such as unmatched surrogates or incomplete combining sequences, and clears the internal buffer.

若要计算存储所生成的GetBytes字符所需的确切缓冲区大小,应用程序应GetByteCount使用。To calculate the exact buffer size that GetBytes requires to store the resulting characters, the application should use GetByteCount.

如果GetBytesflush设置为false的情况下调用,编码器会将结尾字节存储在内部缓冲区中的数据块的末尾,并在下一个编码操作中使用它们。If GetBytes is called with flush set to false, the encoder stores trailing bytes at the end of the data block in an internal buffer and uses them in the next encoding operation. 应用程序应在GetByteCount对同一块调用GetBytes之前立即调用数据块,以便在计算中包括前一块中的任何尾随字符。The application should call GetByteCount on a block of data immediately before calling GetBytes on the same block, so that any trailing characters from the previous block are included in the calculation.

如果你的应用程序要转换输入流的多个段,请考虑Convert使用方法。If your application is to convert many segments of an input stream, consider using the Convert method. GetBytes如果输出缓冲区不够大,将会引发异常,但Convert会尽可能多地填入空间,并返回读取的字符和写入的字节数。GetBytes will throw an exception if the output buffer isn't large enough, but Convert will fill as much space as possible and return the chars read and bytes written. 有关更多Encoding.GetBytes注释,另请参阅主题。Also see the Encoding.GetBytes topic for more comments.

另请参阅

适用于