如何将通用列表序列化为字节数组?
public class CustomerData
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public string CustomerState { get; set; }
public int ProductId { get; set; }
public int QuantityBought { get; set; }
}
List<CustomerData> customerdata = new List<CustomerData>();
我知道这是如何将一个简单的字符串序列化为ByteArray。尝试学习如何执行此操作以获得更复杂的列表和可枚举的内容。
// Input string.
const string input = "Test";
// Invoke GetBytes method.
byte[] array = Encoding.ASCII.GetBytes(input);
我看到了有关将对象转换为字节的技巧,但是我指的是通用列表类。
// Convert an object to a byte array
public static byte[] ObjectToByteArray(Object obj)
{
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
答案 0 :(得分:0)
您可以这样做:
void Main()
{
List<CustomerData> customerdata = new List<CustomerData>();
/*
...Your logic...
...Add Customers to List...
*/
var binaryFormatter = new BinaryFormatter();
var memoryStream = new MemoryStream();
binaryFormatter.Serialize(memoryStream, customerdata);
var result = memoryStream.ToArray();
}
[Serializable]
public class CustomerData
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public string CustomerState { get; set; }
public int ProductId { get; set; }
public int QuantityBought { get; set; }
}