UnicodeEncoding.GetString(Byte[], Int32, Int32) 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
将字节数组中的字节范围解码为字符串。
public:
override System::String ^ GetString(cli::array <System::Byte> ^ bytes, int index, int count);
public override string GetString(byte[] bytes, int index, int count);
[System.Runtime.InteropServices.ComVisible(false)]
public override string GetString(byte[] bytes, int index, int count);
override this.GetString : byte[] * int * int -> string
[<System.Runtime.InteropServices.ComVisible(false)>]
override this.GetString : byte[] * int * int -> string
Public Overrides Function GetString (bytes As Byte(), index As Integer, count As Integer) As String
参数
- bytes
- Byte[]
包含要解码的字节序列的字节数组。
- index
- Int32
要解码的第一个字节的索引。
- count
- Int32
要解码的字节数。
返回
一个 String 对象,包含解码指定字节序列的结果。
- 属性
例外
bytes 是 null (Nothing)。
错误检测已启用,并且 bytes 包含无效的字节序列。
发生回退(有关详细信息,请参阅 .NET 中的字符编码)
-以及-
示例
下面的示例通过调用 GetByteCount 方法来初始化数组,以确定编码字符串所需的字节数,然后添加字节顺序标记(BOM)的大小。 然后,该示例调用 GetPreamble 该方法将 BOM 存储到数组,然后再调用 GetBytes 该方法将编码的字节存储到数组。 然后,该示例调用 GetString 该方法来解码字符串。
using System;
using System.Text;
public class Example
{
public static void Main()
{
UTF8Encoding utf8 = new UTF8Encoding(true, true);
String s = "It was the best of times, it was the worst of times...";
// We need to dimension the array, since we'll populate it with 2 method calls.
Byte[] bytes = new Byte[utf8.GetByteCount(s) + utf8.GetPreamble().Length];
// Encode the string.
Array.Copy(utf8.GetPreamble(), bytes, utf8.GetPreamble().Length);
utf8.GetBytes(s, 0, s.Length, bytes, utf8.GetPreamble().Length);
// Decode the byte array.
String s2 = utf8.GetString(bytes, 0, bytes.Length);
Console.WriteLine(s2);
}
}
// The example displays the following output:
// ?It was the best of times, it was the worst of times...
Imports System.Text
Module Example
Public Sub Main()
Dim utf8 As New UTF8Encoding(True, True)
Dim s As String = "It was the best of times, it was the worst of times..."
' We need to dimension the array, since we'll populate it with 2 method calls.
Dim bytes(utf8.GetByteCount(s) + utf8.GetPreamble().Length - 1) As Byte
' Encode the string.
Array.Copy(utf8.GetPreamble(), bytes, utf8.GetPreamble().Length)
utf8.GetBytes(s, 0, s.Length, bytes, utf8.GetPreamble().Length)
' Decode the byte array.
Dim s2 As String = utf8.GetString(bytes, 0, bytes.Length)
Console.WriteLine(s2)
End Sub
End Module
' The example displays the following output:
' ?It was the best of times, it was the worst of times...
请注意,在这种情况下,解码的字符串不同于原始字符串,因为它以 16 位字节顺序标记 U+FFFD 开头。 这意味着两个字符串将比较为不相等,如果字符串是输出,则 BOM 将显示为替换字符“?”。 若要删除字符串开头的 BOM,可以调用 String.TrimStart 该方法。
注解
在错误检测中,无效序列会导致此方法引发 ArgumentException。 如果没有错误检测,将忽略无效序列,并且不会引发异常。
如果要解码的字节范围包括字节顺序标记(BOM),并且字节数组是由非 BOM 感知类型的方法返回的,则此方法返回的字符 U+FFFE 包含在此方法返回的字符数组中。 可以通过调用 String.TrimStart 该方法将其删除。
要转换的数据(例如从流中读取的数据)可能仅在顺序块中可用。 在这种情况下,或者如果数据量太大,因此需要将其划分为较小的块,则应用程序应分别使用DecoderEncoder或GetDecoderGetEncoder方法提供的对象。