任何对象转换为一个byte [] [英] Convert any object to a byte[]
问题描述
我写了一个原型TCP连接,我有一些麻烦,均质化的数据将被发送。
I am writing a prototype TCP connection and I am having some trouble homogenizing the data to be sent.
目前,我送什么,但字符串,但在未来,我们希望能够发送任何对象。
At the moment, I am sending nothing but strings, but in the future we want to be able to send any object.
在code是目前很简单,因为我以为一切都可以被转换成字节数组:
The code is quite simple at the moment, because I thought everything could be cast into a byte array:
void SendData(object headerObject, object bodyObject)
{
byte[] header = (byte[])headerObject; //strings at runtime,
byte[] body = (byte[])bodyObject; //invalid cast exception
// Unable to cast object of type 'System.String' to type 'System.Byte[]'.
...
}
这当然是很轻松地解决了一个
This of course is easily enough solved with a
if( state.headerObject is System.String ){...}
现在的问题是,如果我这样做的,我需要检查每个类型的对象不能转换为一个byte []在运行时。
The problem is, if I do it that way, I need to check for EVERY type of object that can't be cast to a byte[] at runtime.
由于我不知道能不能转换成一个byte []在运行时的每一个对象,这真的不是一个选项。
Since I do not know every object that can't be cast into a byte[] at runtime, this really isn't an option.
怎样才能把任何物体都成C#.net 4.0?
How does one convert any object at all into a byte array in C# .NET 4.0?
推荐答案
使用的<一个href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter.aspx"><$c$c>BinaryFormatter$c$c>:
private byte[] ObjectToByteArray(Object obj)
{
if(obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
using(MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
这篇关于任何对象转换为一个byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!