8

我需要一个与 Java 中的 ByteBuffer 类似的 C# 实现。感兴趣的方法 - .remaining() - 返回当前位置和限制之间的元素数。- .array() - .clear() - .put(byte[], int, int)

我开始了一些MemoryStream..但没有clear(),还有很多即兴创作另外,我在 Koders 上找到了 ac# 实现:http ://www.koders.com/csharp/fid2F8CB1B540E646746D3ADCB2B0AC867A0A8DCB06.aspx?s=socket#L2 .. 我会使用..但也许你们知道更好的东西

4

3 回答 3

33

MemoryStream可以做你想做的一切:

  • .array()=>.ToArray()
  • .clear()=>.SetLength(0)
  • .put(byte[], int, int)=>.Write(byte[], int, int)
  • .remaining()=>.Length - .Position

如果需要,可以为Clearand创建扩展方法Remaining

public static class MemoryStreamExtensions
{
    public static void Clear(this MemoryStream stream)
    {
        stream.SetLength(0);
    }

    public static int Remaining(this MemoryStream stream)
    {
        return stream.Length - stream.Position;
    }
}
于 2012-04-09T19:31:42.553 回答
3

MemoryStream 应该有你正在寻找的一切。结合 BinaryWriter 写入不同的数据类型。

var ms = new MemoryStream();
ms.SetLength(100);

long remaining = ms.Length - ms.Position; //remaining()

byte[] array = ms.ToArray(); //array()

ms.SetLength(0); //clear()

ms.Write(buffer, index, count); //put(byte[], int, int)
于 2012-04-09T19:32:59.070 回答
-4

你在找一个Queue<T>吗?

http://msdn.microsoft.com/en-us/library/7977ey2c.aspx

对于 Queue 不支持的一些方法,编写一个包装 Queue 的自定义类可能很容易。

于 2012-04-09T19:11:55.253 回答