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;
ms-help://MS.VSCC/MS.MSDNVS.2052/cpref/html/frlrfsystemconvertclasstobytetopic.htm
{
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;
还有,.net并不提供Convert.ToBytes,Convert.ToByte更不可能是我所需要的了。
哪就用字节流方式的序列化方法好了参考
ms-help://MS.VSCC/MS.MSDNVS.2052/cpguide/html/cpconbinaryserialization.htm
private ASCIIEncoding m_ascn ;
//使用
m_ascn.GetChars(chars);
ms-help://MS.VSCC/MS.MSDNVS.2052/cpref/html/frlrfSystemTextASCIIEncodingMembersTopic.htm
就是用XML序列化的方式吧
不管怎么样
都可以当作一个xml格式的文档来解析嘛
实际上如果这样的话,你可以选择:
1、使用XML序列化的方法,在其他开发语言中来解读这个XML文件。
2、实际上你只是想传输数据,那么你应该以数据的保存为中心,可以定义自己的格式来保存数据。另外,如果你使用二进制序列化,只要是在.Net下是绝对可以反序列化的
你的想法和序列化是两个概念!
[StructLayout(LayoutKind.Sequential)]
public struct Test
{
int id;
string name;
char[4] chars = "abcd".ToCharArray();
}
如果这是API的参数,直接用就可以了不用copy到Byte数组。API中用的都是指针(也就是你的struct开头的地址)