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!
Non è chiaro cosa sta succedendo qui. Puoi mostrare il codice che crea l'oggetto, così come il codice che lo decomprime? – cdhowie
Stai ricevendo un array perché "GetBytes" restituisce un array. Che cosa stai cercando di fare esattamente qui perché non è chiaro. –
Ho aggiornato il mio post originale. So che GetBytes restituisce un array, ma voglio restituirlo byte [1] per il mio valore di byte originale. –