假设我有一个 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/