本文介绍了MemoryStream.TryGetBuffer什么时候返回有用的ArraySegment?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bool MemoryStream.TryGetBuffer(out ArraySegment<byte> buffer) 是.NET 4.6中的新API,可用于访问MemoryStream中存储的有效字节,而无需复制它们.这非常令人兴奋!它返回一个布尔值,如果转换成功,则为true;否则为false",并填充out参数.

bool MemoryStream.TryGetBuffer(out ArraySegment<byte> buffer) is a new API in .NET 4.6 that can be used to get access to the valid bytes stored in the MemoryStream without copying them. This is very exciting! It returns a bool that is "true if the conversion was successful; otherwise, false" and populates the out param.

何时返回true,表示out ArraySegment<byte> buffer现在包含有效信息?今天没有记录.

When does it return true, indicating that the out ArraySegment<byte> buffer now contains valid information? This isn't documented today.

我知道,如果它返回false,则可以使用 .ToArray() 以获取字节的副本.而且,我们有 .GetBuffer() ,但是有时MemoryStream会在缓冲区中创建偏移量,并且此信息很难( )以供以后使用,更不用说要提高鲁棒性的try ... catch.

I know that if it returns false, I can use .ToArray() to get a copy of the bytes. And, we've have .GetBuffer(), but sometimes MemoryStreams are created with an offset into the buffer, and this information is hard (well, sort of) to get later on, not to mention the try ... catch needed for robustness.

推荐答案

为使TryGetBuffer执行成功的转换并使用有用的信息填充out参数,缓冲区必须可见.如果使用以下任何构造函数,则该缓冲区可见:

For TryGetBuffer to perform a successful conversion and populate the out param with useful information, the buffer must be visible. The buffer is visible if any of these constructors are used:

  • MemoryStream()
  • MemoryStream(int capacity)
  • MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible)publiclyVisible: true.
  • MemoryStream()
  • MemoryStream(int capacity)
  • MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) with publiclyVisible: true.

检查源代码更多细节.

这篇关于MemoryStream.TryGetBuffer什么时候返回有用的ArraySegment?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 04:47