我需要将代码从 Java 移植到 C#。在 Java 代码中,使用了“ByteBuffer.flip()”和“ByteBuffer.slice”方法,我不知道如何翻译。
我已经阅读了这个问题(相当于 c# 中的 javax.nio.Buffer.flip()),但是虽然给出了答案,但我不知道如何应用它。根据 Tom Hawtin 的说法,我应该在基础数组中“将限制设置为当前位置,然后将位置设置为零”。我不确定如何更改这些值。(如果您能解释基本逻辑,那将对我有很大帮助:)
至于 ByteBuffer.slice,我不知道如何翻译它。
编辑:如果实际代码更清楚,我会发布它:
爪哇:
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
谢谢!
编辑:更改b.BaseStream.SetLength(b.BaseStream.Length);
为b.BaseStream.SetLength(b.BaseStream.Position);
,基于 Java 文档。