2013-08-02 73 views
7

我正在使用Convert an array of different value types to a byte array解決方案爲我的對象進行字節數組轉換。C#將object []轉換爲byte [],但如何將字節對象保存爲byte?

但我有一個小問題,導致一個大問題。

對象[]的mids中存在「字節」類型的數據,我不知道如何保留「字節」。我需要保持相同的字節長度前後。

我嘗試添加「字節」型到字典是這樣的:

private static readonlyDictionary<Type, Func<object, byte[]>> Converters = 
    new Dictionary<Type, Func<object, byte[]>>() 
{ 
    { typeof(byte), o => BitConverter.GetBytes((byte) o) }, 
    { typeof(int), o => BitConverter.GetBytes((int) o) }, 
    { typeof(UInt16), o => BitConverter.GetBytes((UInt16) o) }, 
    ... 
}; 
public static void ToBytes(object[] data, byte[] buffer) 
{ 
    int offset = 0; 

    foreach (object obj in data) 
    { 
     if (obj == null) 
     { 
      // Or do whatever you want 
      throw new ArgumentException("Unable to convert null values"); 
     } 
     Func<object, byte[]> converter; 
     if (!Converters.TryGetValue(obj.GetType(), out converter)) 
     { 
      throw new ArgumentException("No converter for " + obj.GetType()); 
     } 

     byte[] obytes = converter(obj); 
     Buffer.BlockCopy(obytes, 0, buffer, offset, obytes.Length); 
     offset += obytes.Length; 
    } 
} 

沒有SYNTEXT抱怨,但我跟蹤這個代碼,程序執行

byte[] obytes = converter(obj); 

原件後「字節「變爲字節[2]。

這裏會發生什麼?如何在此解決方案中保持字節值真實?

謝謝!

+1

目前還不清楚這裏發生了什麼。你能顯示創建對象的代碼,以及解壓縮它的代碼嗎? – cdhowie

+0

你得到一個數組,因爲'GetBytes'返回一個數組。你究竟在這裏做什麼,因爲它不明確。 –

+0

我更新了我的原始帖子。我知道GetBytes返回一個數組,但我希望它返回字節[1]爲我的重要字節值。 –

回答

14

沒有BitConverter.GetBytes重載需要一個byte,因此您的代碼:

BitConverter.GetBytes((byte) o) 

是被隱式擴展到最接近的匹配:BitConverter.GetBytes(short)Int16),導致兩個字節。您只需返回一個單元素字節數組,例如像這樣:

{ typeof(byte), o => new[] { (byte) o } } 
+0

謝謝大家。有用。我不明白這個lambda的事情。 –