简体   繁体   English

避免将偏移量传递给C#MemoryStream写

[英]avoiding passing offset to C# MemoryStream write

I have a MemoryStream object that is getting passed around from function to function, and each function adds something to it (could be byte could be more). 我有一个MemoryStream对象,该对象从一个函数传递到另一个函数,每个函数都向它添加一些内容(可能是字节,也可能更多)。
There are matching functions in read. 读取中有匹配功能。

Can I avoid updating the offset by myself and let "the stream" handle it? 我可以避免自己更新偏移量,而让“流”对其进行处理吗?
(such as stream.Write(byte[]); similar to stream.WriteByte(byte); ) (例如stream.Write(byte[]);类似于stream.WriteByte(byte);

I'm a bit confused from all the documentation in the area 我对该地区的所有文档有些困惑

Yes, you can create an extension method that always sets the offset to 0(ie writes from the zero index in the buffer). 是的,您可以创建一个扩展方法 ,该方法始终将偏移量设置为0(即,从缓冲区中的零索引开始写入)。

public static class Extensions
{
    public static void Write(this MemoryStream stream, byte[] buffer)
    {
        stream.Write(buffer, 0, buffer.Length);
    }
}

Yes, you can avoid passing the offset around. 是的,您可以避免传递偏移量。

When you write to a memory stream, its Position property is incremented by the size of the item(s) written, so the next one written will be after the previous one. 当您写入内存流时,其Position属性会增加写入项的大小,因此下一个写入项将在前一个写入项之后。

You can therefore just pass around the memory stream. 因此,您可以只传递内存流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM