将通用类列表序列化为字节数组

时间:2018-09-24 16:06:50

标签: c# serialization

如何将通用列表序列化为字节数组?

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

1 个答案:

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