运行下面的代码时:为什么简单类型的序列化如此复杂?
int myInt = 13;
object myObj = myInt;
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
System.IO.MemoryStream ms = new System.IO.MemoryStream();
bf.Serialize(ms, myObj);
byte[] myByteArray = ms.ToArray();
你得到一个数组,其长度为54个字节 - 我不明白你为什么不拿到4个字节长度的数组。
即使您尝试序列化int变量(而不是对象变量),如下所示: bf.Serialize(ms,myInt);
你会得到同样的结果。 我的目标是不同类型(的Int32,Int16类型等)转换为字节数组,所以我不能使用
BitConverter.GetBytes(myObj);
,因为它不会编译:
Error 1 The best overloaded method match for 'System.BitConverter.GetBytes(bool)' has some invalid arguments...
这是显而易见的,因为编译器无法明确地告诉它,不能将对象转换为别的东西...
我在做什么错?