简体   繁体   English

如何将Collection转换为字节数组

[英]How to convert a Collection to byte array

I have an ObservableCollection<Employee> how do I convert it into byte array[]? 我有一个ObservableCollection<Employee>如何将其转换为字节数组[]?

The class Employee consists of, - EmployeeId - DateOfJoining - Age - Salary Employee类包括:-EmployeeId-DateOfJoining-年龄-工资

The service I need to pass the collection to is expecting the data to be in byte[]. 我需要将集合传递给的服务期望数据在byte []中。
What would be an efficient way to convert observableCollection to byte[]? 将observableCollection转换为byte []的有效方法是什么?
Or do I just need to loop through the collection to create a byte array? 还是只需要遍历集合以创建字节数组?

you can use a Binary Formatter to serialize your collection. 您可以使用二进制格式化程序来序列化您的集合。

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter.aspx http://msdn.microsoft.com/zh-CN/library/system.runtime.serialization.formatters.binary.binaryformatter.aspx

var employees = new ObservableCollection<Employee>();


using (var stream = new MemoryStream())
{    
    var formatter = new BinaryFormatter();
    formatter.Serialize(stream, employees);
    var byteArray = new byte[stream.Length];
    stream.Seek(0, SeekOrigin.Begin);
    stream.Read(byteArray, 0, (int)stream.Length);
    // do whatever you want with the bytes now....

}

You have choices like Protobuf, Protobuf-Net, your own custom BinaryWriter "ToBytes, FromBytes". 您可以选择Protobuf,Protobuf-Net,自己的自定义BinaryWriter“ ToBytes,FromBytes”。 It really depends on what your receiving end desires, and whether they are using a generic documented format or a custom one. 这实际上取决于接收端的需求,以及它们使用的是通用文档格式还是定制格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM