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 該方法來移除它。
待轉換的資料,例如從串流讀取的資料,可能只能以連續區塊形式取得。 在這種情況下,或資料量過大需要分割成較小區塊時,應用程式應分別使用 Decoder 或 Encoder 或 方法所提供的GetDecoderGetEncoder物件。