gpt4 book ai didi

c# - 将任何对象转换为 byte[]

转载 作者:IT王子 更新时间:2023-10-29 03:33:33 26 4
gpt4 key购买 nike

我正在编写一个原型(prototype) TCP 连接,但在对要发送的数据进行均质化时遇到了一些问题。

目前,我只发送字符串,但将来我们希望能够发送任何对象。

目前代码非常简单,因为我认为所有内容都可以转换为字节数组:

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[]'.
...
}

这当然很容易用

解决
if( state.headerObject is System.String ){...}

问题是,如果我那样做,我需要检查无法在运行时转换为 byte[] 的每种类型的对象。

因为我不知道在运行时不能转换为 byte[] 的每个对象,所以这确实不是一个选项。

如何将任何对象转换为 C# .NET 4.0 中的字节数组?

最佳答案

使用 BinaryFormatter :

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();
}
}

请注意,objobj 中的任何属性/字段(以及它们的所有属性/字段等等)都需要使用 Serializable attribute 进行标记以以此成功连载。

关于c# - 将任何对象转换为 byte[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4865104/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com