将对象数组转换为字节数组

3
我有一个包含不同类型数组的对象数组,在编译时无法确定其类型,但实际上是int[]double[]等。
我想将这些数组保存到磁盘上,并且不需要在线处理它们的内容,因此我正在寻找一种将object[]转换为byte[]的方法,然后可以将其写入磁盘。
如何实现这一点?
3个回答

3
你可以使用二进制序列化和反序列化来处理可序列化类型。
using System.Runtime.Serialization.Formatters.Binary;

BinaryFormatter binary = BinaryFormatter();
using (FileStream fs = File.Create(file))
{
    bs.Serialize(fs, objectArray);
}

编辑:如果数组的所有元素都是简单类型,则使用BitConverter。
object[] arr = { 10.20, 1, 1.2f, 1.4, 10L, 12 };
using (MemoryStream ms = new MemoryStream())
{
    foreach (dynamic t in arr)
    {
        byte[] bytes = BitConverter.GetBytes(t);
        ms.Write(bytes, 0, bytes.Length);
    }
}

我的实现被迫在数据写入之前转换为字节数组,因为实际的写入是由另一个类完成的。 - kasperhj
使用MemoryStream代替FileStream。您可以在帖子中添加示例数据。 - KV Prajapati
我非常确定这个代码会做其他事情而不仅仅是序列化数值。我已经尝试过了,对于一个包含两个整数的对象数组,我得到了一个39字节流! - kasperhj
你可以使用 BitConverter.GetBytes 方法(适用于所有简单类型)。 - KV Prajapati

2
你可以用老式的方法来做。
static void Main()
{
  object [] arrayToConvert = new object[] {1.0,10.0,3.0,4.0, 1.0, 12313.2342};

  if (arrayToConvert.Length > 0) {
     byte [] dataAsBytes;
     unsafe {
        if (arrayToConvert[0] is int) {
           dataAsBytes = new byte[sizeof(int) * arrayToConvert.Length];
           fixed (byte * dataP = &dataAsBytes[0]) 
              // CLR Arrays are always aligned
              for(int i = 0; i < arrayToConvert.Length; ++i) 
                 *((int*)dataP + i) = (int)arrayToConvert[i];
        } else if (arrayToConvert[0] is double) {
           dataAsBytes = new byte[sizeof(double) * arrayToConvert.Length];
           fixed (byte * dataP = &dataAsBytes[0]) {
              // CLR Arrays are always aligned
              for(int i = 0; i < arrayToConvert.Length; ++i) {
                 double current = (double)arrayToConvert[i];
                 *((long*)dataP + i) = *(long*)&current;        
              }
           }
        } else {
           throw new ArgumentException("Wrong array type.");
        }
     }

     Console.WriteLine(dataAsBytes);
  }
}

然而,我建议您重新考虑您的设计。您可能应该使用泛型,而不是对象数组。


我喜欢这个,但我会创建MemoryStream并使用BinaryWriter来写入它... 很好,干净,紧密打包。 - Daniel Mošmondor

0

这里开始:

List<object> list = ...
byte[] obj = (byte[])list.ToArray(typeof(byte));

或者,如果您的列表是复杂类型:

list.CopyTo(obj);

没有接受参数的 ToArray 的重载。 - kasperhj
从文档链接来看,OfType 是用于过滤而非转换的。实际上,运行您的代码片段会产生一个空的 obj - kasperhj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接