我需要将Java代码移植到C#中。在Java代码中,使用了"ByteBuffer.flip()"和"ByteBuffer.slice"方法,但我不知道如何翻译这些方法。
我已经阅读了这篇问题(An equivalent of javax.nio.Buffer.flip() in c#),尽管有答案,但我无法理解如何应用它。根据Tom Hawtin的说法,我应该在底层数组中“将限制设置为当前位置,然后将位置设置为零”。我不确定如何更改这些值。(如果您能解释其中的逻辑,那会对我很有帮助:)
至于ByteBuffer.slice,则不知道如何翻译它。
编辑:如果实际代码可以更清晰地表达问题,我会发布它:
Java:
我已经阅读了这篇问题(An equivalent of javax.nio.Buffer.flip() in c#),尽管有答案,但我无法理解如何应用它。根据Tom Hawtin的说法,我应该在底层数组中“将限制设置为当前位置,然后将位置设置为零”。我不确定如何更改这些值。(如果您能解释其中的逻辑,那会对我很有帮助:)
至于ByteBuffer.slice,则不知道如何翻译它。
编辑:如果实际代码可以更清晰地表达问题,我会发布它:
Java:
ByteBuffer buff;
buff.putShort((short) 0);
buff.put(customArray);
buff.flip();
buff.putShort((short) 0);
ByteBuffer b = buff.slice();
short size = (short) (customFunction(b) + 2);
buff.putShort(0, size);
buff.position(0).limit(size);
到目前为止,我在C#.NET上的翻译:
BinaryWriter b = new BinaryWriter(); //ByteBuffer buff;
b.Write((short)0); // buff.putShort((short) 0);
b.Write(paramStream.ToArray()); // buff.put(customArray);
b.BaseStream.SetLength(b.BaseStream.Position); // buff.flip; (not sure)
b.BaseStream.Position = 0; // buff.flip; too (not sure)
b.Write((short)0); // buff.putShort((short) 0)
??? // ByteBuffer b = buff.slice();
// Not done but I can do it, short size = (short) (customFunction(b) + 2);
??? // How do I write at a particular position?
??? // buff.position(0).limit(size); I don't know how to do this
谢谢你!
编辑:根据Java文档,将b.BaseStream.SetLength(b.BaseStream.Length);
更改为b.BaseStream.SetLength(b.BaseStream.Position);
。