2013-08-02 11 views
7

Sto utilizzando la soluzione Convert an array of different value types to a byte array per i miei oggetti alla conversione di array di byte.C# converte oggetto [] in byte [], ma come mantenere l'oggetto byte come byte?

Ma ho un piccolo problema che causa un grosso problema.

Ci sono tipi di dati "byte" in midi di oggetto [], non so come mantenere "byte" così come sono. Ho bisogno di mantenere la stessa lunghezza dei byte prima e dopo.

ho cercato aggiuntivo di tipo "byte" nel dizionario come questo:

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; 
    } 
} 

non c'è Syntext lamentarsi, ma ho rintracciato questo codice, dopo che il programma eseguito

byte[] obytes = converter(obj); 

l'originale " byte "diventa byte [2].

Cosa succede qui? Come mantenere il valore del byte autentico in questa soluzione?

Grazie!

+1

Non è chiaro cosa sta succedendo qui. Puoi mostrare il codice che crea l'oggetto, così come il codice che lo decomprime? – cdhowie

+0

Stai ricevendo un array perché "GetBytes" restituisce un array. Che cosa stai cercando di fare esattamente qui perché non è chiaro. –

+0

Ho aggiornato il mio post originale. So che GetBytes restituisce un array, ma voglio restituirlo byte [1] per il mio valore di byte originale. –

risposta

14

Non c'è BitConverter.GetBytes overload che accetta un byte, quindi il codice:

BitConverter.GetBytes((byte) o) 

si sta implicitamente ampliato in partita più vicino: BitConverter.GetBytes(short) (Int16), con conseguente due byte. Tutto ciò che devi fare è restituire un array di byte a elemento singolo, ad es. così:

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

Grazie a tutti. Funziona. Non ho capito questa cosa lambda. –