如何将列表转换为字节? [英] how to convert list to bytes ?

查看:81
本文介绍了如何将列表转换为字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的客户中,我要转换列表<>到字节,以便发送到我的服务器,以及如何将字节转换为list<>
可能对您有用:)

In my client, I want convert list<> to bytes so that send to my server and how to convert bytes to list<>
May you help me :)

推荐答案

小子,

确保通用列表中的类型可序列化.然后执行以下操作:

Hi Kid,

make sure the type in your generic list is serializable. Then do this:

List<yourtype> itemsToSerialize = new List<yourtype>();
itemsToSerialize.Add ( new yourtype() );
itemsToSerialize.Add ( new yourtype() );

Stream stream = new FileStream( @"MyApplicationData.dat", System.IO.FileMode.Create );
IFormatter formatter = new BinaryFormatter();
formatter.Serialize( stream, itemsToSerialize );

stream.Close();
</yourtype></yourtype>



本示例使用一个文件.但是您可以轻松地将其改写为写入套接字.这是将反序列化List< yourtype>的部分.来自文件:



This sample uses a file. But you can easyly adapt it to write to a socket instead. Here is the part that would deserialize List<yourtype> from a file:

Stream stream = new FileStream( @"MyApplicationData.dat", System.IO.FileMode.Open );

IFormatter formatter = new BinaryFormatter();
List<yourtyoe> itemsDeserialized = (List<yourtype>)formatter.Deserialize( stream );
stream.Close();
</yourtype></yourtyoe>



同样,您必须改用插座来代替它.

希望这会有所帮助!

欢呼声

Manfred



Again this will have to be adapted by you to utilize a socket instead.

Hope this helps!

Cheers

Manfred


听起来您想使用BinaryFormatter类来序列化和反序列化List<>放入可以发送到您的服务器的MemoryStream中:
It sounds like you want to use the BinaryFormatter class to serialize and deserialize your List<> into a MemoryStream that can be sent to your server: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter%28VS.71%29.aspx[^]

Also: You need to be sure that the object type the list contains is serializable (meaning they have the [SerializableAttribute()] applied to them).


这篇关于如何将列表转换为字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆