首页 文章

字节集合与java中的ByteBuffer类似

提问于
浏览
8

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

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

3 回答

  • 27

    你在找 Queue<T> 吗?

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

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

  • 3

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

相关问题