UTF8Encoding.GetString(Byte[], Int32, Int32) 方法

定义

将字节数组中某个范围的字节解码为一个字符串。

C#
public override string GetString(byte[] bytes, int index, int count);
C#
[System.Runtime.InteropServices.ComVisible(false)]
public override string GetString(byte[] bytes, int index, int count);

参数

bytes
Byte[]

包含要解码的字节序列的字节数组。

index
Int32

第一个要解码的字节的索引。

count
Int32

要解码的字节数。

返回

包含指定字节序列解码结果的 String

属性

例外

bytesnull

indexcount 小于零。

indexcount 不表示 bytes 中的有效范围。

启用了错误检测,并且 bytes 包含无效的字节序列。

发生回退(有关详细信息,请参阅采用 .NET 的字符编码

-和-

DecoderFallback 设置为 DecoderExceptionFallback

示例

以下示例通过调用 GetByteCount 方法初始化数组,以确定编码字符串所需的字节数,然后将字节顺序标记的大小添加到 BOM) (。 然后,该示例调用 GetPreamble 方法将 BOM 存储到数组,然后调用 GetBytes 方法将编码的字节存储到数组。 然后,该示例调用 GetString 方法来解码字符串。

C#
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...

请注意,在这种情况下,解码的字符串不同于原始字符串,因为它以 16 位字节顺序标记 U+FFFD 开头。 这意味着这两个字符串将比较为不相等,如果输出字符串,则 BOM 将显示为替换字符“?”。 若要删除的字符串的开始处的 BOM,可以调用String.TrimStart方法。

注解

使用错误检测时,无效序列会导致此方法引发 ArgumentException 异常。 如果不进行错误检测,将忽略无效序列,并且不会引发异常。

如果要解码的字节范围包括 BOM) (字节顺序标记,并且字节数组是由非 BOM 感知类型的方法返回的,则字符 U+FFFE 包含在此方法返回的字符数组中。 可以通过调用 String.TrimStart 方法将其删除。

要转换的数据(例如从流读取的数据)可能仅在顺序块中可用。 在这种情况下,或者如果数据量太大,需要将其划分为较小的块,请分别使用 Decoder 方法或 Encoder 方法提供的 GetDecoderGetEncoder

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

另请参阅