byte []到强类型数组?

时间:2012-03-02 10:51:49

标签: c# serialization byte

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

  1. 我有一个数组,它已被多头连接成一个大字节[]数组并存储在一个表中。
  2. 我想读取这个byte []数组,但将其转换为强类型数组。
  3. 由于我将整个数组存储为byte []数组,我是否可以读取该字节数组并将其转换为强类型版本? 目前返回null ...

    一次点击可能吗?

    提前致谢,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>
    

2 个答案:

答案 0 :(得分:0)

很可能就是

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

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

答案 1 :(得分:0)

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

我不知道你的序列化方法是如何工作的,但你可能只是改变代码:

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

要:

_ByteCollection.Add(Serialise(Array));

这应该有用,那么你可以稍微简化一下。