2012-03-02 66 views
-1

我在将大型字节数组转换为强类型数组时遇到了一些问题。byte []强类型数组?

  1. 我有一个数组已被concatinated到一个大的byte []数组中,并存储在一个表中。
  2. 我想然后读取此byte []数组,但将其转换为强类型数组。

因为我已经将整个数组存储为byte []数组,所以我不能读取该字节数组并将其转换为强类型版本吗? 目前其返回空...

这是可能的一击中?

在此先感谢,Onam。

<code> 
    #region Save 
    public void Save<T>(T[] Array) where T : new() 
    { 
     List<byte[]> _ByteCollection = new List<byte[]>(); 
     byte[] _Bytes = null; 
     int _Length = 0; 
     int _Offset = 0; 

     foreach (T _Item in Array) 
     { 
      _ByteCollection.Add(Serialise(_Item)); 
     } 
     foreach (byte[] _Byte in _ByteCollection) 
     { 
      _Length += _Byte.Length; 
     } 

     _Bytes = new byte[_Length]; 

     foreach (byte[] b in _ByteCollection) 
     { 
      System.Buffer.BlockCopy(b, 0, _Bytes, _Offset, b.Length); 
      _Offset += b.Length; 
     } 
     Customer[] c = BinaryDeserialize<Customer[]>(_Bytes); 
    } 
    #endregion 

    #region BinaryDeserialize 
    public static T BinaryDeserialize<T>(byte[] RawData) 
    { 
     T _DeserializedContent = default(T); 

     BinaryFormatter _Formatter = new BinaryFormatter(); 
     try 
     { 
      using (MemoryStream _Stream = new MemoryStream()) 
      { 
       _Stream.Write(RawData, 0, RawData.Length); 
       _Stream.Seek(0, SeekOrigin.Begin); 
       _DeserializedContent = (T)_Formatter.Deserialize(_Stream); 
      } 
     } 
     catch (Exception ex) 
     { 
      _DeserializedContent = default(T); 
     } 

     return _DeserializedContent; 
    } 
    #endregion 
</code> 
+0

你在调试器中看到什么? – 2012-03-02 10:57:40

+1

a byte []是一个强类型数组(它的类型是字节数组) – 2012-03-02 11:00:24

+0

我的save方法循环遍历一个Customer数组,并将每个Customer(表示为byte [])复制到另一个数组(表示它们的一个数组)。我正在将SAME的巨大数组byte []传递给Deserialize方法。我希望在这里反序列化到客户数组[...] – 2012-03-02 11:09:28

回答

0

我认为问题是,你正在序列化每个项目到一个列表,然后连接字节。当这是反序列化时,这看起来就像一个客户的数据加上一些意外的数据(其他客户)。

我不知道你的序列化方法的作品,但你可能只需要更改代码:

foreach (T _Item in Array) 
    { 
     _ByteCollection.Add(Serialise(_Item)); 
    } 

要:

_ByteCollection.Add(Serialise(Array)); 

,并应工作,那么你很可能把它简化小。

+1

耶稣基督ARGH !! !哎呀!哎呀! ARGH ARGH ARGH ARGH ARGH !!!是!!!这已经整理它!不能相信这是因为那个ARGH !!!! :'(非常感谢你,我不敢相信,我一直在盯着它,因为我的大脑已经正式变成了果冻! – 2012-03-02 11:17:28

0

最有可能的线

_DeserializedContent = (T)_Formatter.Deserialize(_Stream); 

抛出异常。在catch块中,你只需吞下并忽略该异常。

+0

是的,这是返回null,但是我使用从Save方法生成的相同的byte []数组反序列化... – 2012-03-02 11:02:08