簡體   English   中英

在字節數組的頂部疊加一個 stream

[英]Superimpose a stream on top of a byte array

C#/.NET 中是否有任何方法可以“疊加” - 或 map - 在現有byte[]之上的MemoryStream ,這樣就不會不必要地復制數據?

在嘗試將byte[]轉換為 stream 時,標准解決方案是使用MemoryStream及其Write function,如下所示:

byte[] myArray = new byte[10]; // or, e.g. retrieve from DB
MemoryStream stream = new MemoryStream();
stream.Write(myArray, 0, myArray.Length);

或者,這可以縮短為:

byte[] myArray = new byte[10]; // or, e.g. retrieve from DB
MemoryStream stream = new MemoryStream(myArray);

這真的是一回事。

這存在必須將數組的全部內容復制到 stream 中的問題,因此會使用 2X 數量的 memory。 考慮到字節數組可能非常大,這似乎並不令人滿意。 數據已經在 memory 中,在一個連續的塊中,所以......

memory stream 可以以某種方式就地映射到字節數組嗎?

您在第二個塊中提到的MemoryStream構造函數實際上可以執行您想要的操作。 它保存您提供的數組並將其用作 stream 的后備緩沖區。 您可以修改數組,如果這些字節仍未被讀取,這些更改將由 stream 反映。

這是一個最小的可重現示例來證明這一點。

byte[] source = new byte[] { 0, 1, 2, 3 };
MemoryStream stream = new MemoryStream(source);

// If the constructor made a copy, the stream won't be
// affected and it will output 0 below.
source[0] = 10;

byte b = (byte)stream.ReadByte();

Console.WriteLine(b);

Output:

10

試試看!

請注意,使用該構造函數時 stream 無法增長。 根據其文檔

stream的長度不能設置為大於指定字節數組初始長度的值; 但是,可以截斷 stream(參見 SetLength)。

允許它增長將打破它正在使用該緩沖區的期望,因為增長將需要分配一個新數組並將數據復制到它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM