2017-03-01 103 views
0

我有以下功能將原始數組類型轉換爲字節數組,所以我可以將它轉換爲base64字符串,然後將它存儲在某處,反之亦然,而且我卡住了現在因爲我必須轉換不是原始類型的十進制類型。我意識到,十進制基本上是一個結構,所以我會將結構數組轉換爲字節數組,但我只看到使用不安全的代碼的答案,我想盡可能避免這種情況。我用的團結,我也僅限於.NET 2.0將十進制數組轉換爲字節數組,反之亦然在C#

private static string ConvertArrayToBase64<T>(ICollection<T> array) where T : struct 
    { 
     if (!typeof(T).IsPrimitive) 
      throw new InvalidOperationException("Only primitive types are supported."); 

     int size = Marshal.SizeOf(typeof(T)); 
     var byteArray = new byte[array.Count * size]; 
     Buffer.BlockCopy(array.ToArray(), 0, byteArray, 0, byteArray.Length); 
     return Convert.ToBase64String(byteArray); 
    } 

    private static T[] ConvertBase64ToArray<T>(string base64String) where T : struct 
    { 
     if (!typeof(T).IsPrimitive) 
      throw new InvalidOperationException("Only primitive types are supported."); 

     var byteArray = Convert.FromBase64String(base64String); 
     var array = new T[byteArray.Length/Marshal.SizeOf(typeof(T))]; 
     Buffer.BlockCopy(byteArray, 0, array, 0, byteArray.Length); 
     return array; 
    } 

回答

2

您應該考慮使用System.IO.BinaryReaderSystem.IO.BinaryWriter。這些將使您能夠讀寫基本信息到另一個流,例如System.IO.MemoryStream,然後您可以訪問二進制數據並將其轉換爲基本64,其中Convert.ToBase64String()

+0

通過寫入陣列的大小爲INT然後通過小數陣列環繞寫的其餘部分,和讀出該第一INT時解決了它代表返回a的大小rray。 –

0

您可以將幾乎任何對象序列化並反序列化爲字節,XML,JSON等

static byte[] serialize<T>(T t) 
{ 
    var serializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 
    using (var ms = new MemoryStream()) 
    { 
     serializer.Serialize(ms, t); 
     return ms.ToArray();    
    } 
} 

static object deserialize(byte[] bytes) 
{ 
    var serializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 
    using (var ms = new MemoryStream(bytes)) 
     return serializer.Deserialize(ms); 
} 

[Serializable] class arrays { public decimal[] decArray; public int[] intArray; } 

樣品使用

arrays a = new arrays(); 
a.decArray = new decimal[] { 1m, 2m }; 
a.intArray = new int[] { 3, 4 }; 

byte[] bytes = serialize(a); 


arrays result = deserialize(bytes) as arrays; 

Debug.Print($"{string.Join(", ", result.decArray)}\t{string.Join(", ", result.intArray)}"); 
相關問題