将任何对象转换为字节[] [英] Convert any object to a byte[]

查看:24
本文介绍了将任何对象转换为字节[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个原型 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.

目前代码很简单,因为我认为一切都可以转换成字节数组:

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

这当然很容易用

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?

推荐答案

使用 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 属性 用这个成功序列化.

Note that obj and any properties/fields within obj (and so-on for all of their properties/fields) will all need to be tagged with the Serializable attribute to successfully be serialized with this.

这篇关于将任何对象转换为字节[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆