【问题标题】:byte collection based similar with ByteBuffer from java基于类似于来自java的ByteBuffer的字节集合
【发布时间】:2012-04-09 19:07:19
【问题描述】:

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

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

【问题讨论】:

  • put->Writeclear->Position=0array()->ToArray() 等。我看不出你不能用 MemoryStream 做什么。
  • @L.B,将 Position 设置为 0 不等于 clear... 但 SetLength(0) 将是

标签: c# java bytebuffer


【解决方案1】:

MemoryStream 可以为所欲为:

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

如果需要,您可以为ClearRemaining 创建扩展方法:

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;
    }
}

【讨论】:

  • ByteBuffer.allocate(int) 呢?
  • @Paul, new MemoryStream(int)
【解决方案2】:

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)

【讨论】:

    【解决方案3】:

    您在寻找Queue<T>吗?

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

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

    【讨论】:

    • 队列只允许添加和删除单个元素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 2014-12-23
    • 2013-02-25
    • 2019-07-06
    • 2015-07-21
    相关资源
    最近更新 更多