MoS*_*She 0 c# arrays deserialization
我有一个字节数组,我需要将其反序列化为几种对象类型。
该对象包含{float,short,int}。在Java中,我可以这样ObjectInputStream:
ObjectInputStream is;
is.readFloat()
is.readShort()
is.readInt()
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种用C#做到这一点的方法。
读取第一个x字节为float,下一个y字节为short,下一个z字节为int。
您想使用BinaryReader:
如果您有要反序列化的字节数组,则将其包装在内存流中,然后使用BinaryReader。像这样:
byte[] inputArray; // somehow you've obtained this
using (var inputStream = new MemoryStream(inputArray))
{
using (var reader = new BinaryReader(inputStream))
{
float f1 = reader.ReadSingle();
short s1 = reader.ReadInt16();
int i1 = reader.ReadInt32();
}
}
Run Code Online (Sandbox Code Playgroud)
您也可以使用BitConverter类来执行此操作,但是必须保持状态。例如,你可以阅读float,一short,和int这样的:
byte[] inputArray;
int ix = 0;
float f1 = BitConverter.ToSingle(inputArray, ix);
ix += sizeof(float); // increment to the next value
short s1 = BitConverter.ToInt16(inputArray, ix);
ix += sizeof(short);
int i1 = BitConverter.ToInt32(inputArray, ix);
ix += sizeof(int);
Run Code Online (Sandbox Code Playgroud)
在这两种方法中,我建议您使用BinaryReader,因为在大多数情况下,它更加灵活且易于使用。BitConverter如果您只有少量要反序列化的项目,则非常方便。我认为它具有更快的潜力,但这并不重要,除非您的应用程序对性能高度敏感。如果对数据进行反序列化至关重要,则可能需要编写一个自定义反序列化器。