c# - 安全访问 MemoryStream 中的数据

标签 c# arrays memorystream

假设我有一个 MemoryStream 和对字节进行操作的函数。

目前的代码是这样的:

void caller()
{
    MemoryStream ms = // not important
    func(ms.GetBuffer(), 0, (int)ms.Length);
}

void func(byte[] buffer, int offset, int length)
{
    // not important
}

我无法更改 func 但我想尽量减少从 func 中更改流数据的可能性。

我如何/应该如何重写代码以确保流数据不会被更改?

或者这不能完成?

编辑:

抱歉,我没有提到我不想复制数据。

最佳答案

调用.ToArray .

func(ms.GetBuffer().ToArray(), 0, (int)ms.Length);

来自 MSDN (强调我的):

Note that the buffer contains allocated bytes which might be unused. For example, if the string "test" is written into the MemoryStream object, the length of the buffer returned from GetBuffer is 256, not 4, with 252 bytes unused. To obtain only the data in the buffer, use the ToArray method; however, ToArray creates a copy of the data in memory.


理想情况下,您会更改 func采取IEnumerable<byte> .一旦方法拥有数组,您就相信如果您不希望它们修改数据,它们将不会修改。如果契约(Contract)提供IEnumerable<byte> ,实现者必须决定是否需要编辑副本。

关于c# - 安全访问 MemoryStream 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12304602/

相关文章:

c# - 在 Live SDK 中使用异步/等待

C# HttpClient.SendAsync 等待抛出 NullReferenceException

c# - 如何将通用列表中同一接口(interface)的各种派生类作为参数传递给函数?

java - 如何使弹跳球与处理中的矩形数组碰撞?

c# - 无法访问关闭的流?

c# - 将数据从 MemoryStream 直接复制到 BinaryWriter.BaseStream?

c# - 无效的转换异常,没有重定向或警报

java - 创建双泛型数组 - Java

javascript - 计算对象数组中相对于另一个属性的唯一属性出现次数

c# - 通过 BinaryReader 将字节数组解压缩为字符串会产生空字符串