class Test
{
int id;
string name;
char[] chars = "abcd".ToCharArray();
}
声明为可序列化:
[Serializable]
class Test
{
int id;
string name;
char[] chars = "abcd".ToCharArray();
}
然后在转换的地方:
MemoryStream stream = new MemoryStream();
IFormatter formatter = new BinaryFormatter();
Test t = new Test();
formatter.Serialize( stream,t );
stream.Flush();
byte[] theBytes = stream.ToArray();
stream.Close();
//theBytes 就是序列化后的字节数组
反序列化:
IFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream( theBytes ); //theBytes是序列化后的结果
Test t = (Test) formatter.Deserialize(fromStream);
stream.Close();
//t 就是反序列化后的对象
另外,使用上面这些类,需要引用:
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
序列化对象传输
最新推荐文章于 2024-07-15 21:55:17 发布