如何将对象转换为C#中的字节数组 [英] How to convert an object to a byte array in C#

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

问题描述

我有我需要写一个二进制文件对象的集合。

I have a collection of objects that I need to write to a binary file.

我需要的文件中的字节是紧凑的,所以我不能使用的BinaryFormatter 的BinaryFormatter 罚全中,为反序列化需求的各种信息的。

I need the bytes in the file to be compact, so I can't use BinaryFormatter. BinaryFormatter throws in all sorts of info for deserialization needs.

如果我尝试

byte[] myBytes = (byte[]) myObject 

我得到一个运行时异常。

I get a runtime exception.

我需要这要快,所以我宁愿不被复制周围的字节数组。我只是想投字节[] = myBytes(字节[])myObject的工作!

I need this to be fast so I'd rather not be copying arrays of bytes around. I'd just like the cast byte[] myBytes = (byte[]) myObject to work!

OK仅仅是明确的,我不能要的在输出文件中的任何的元数据。就在对象中的字节。填充对象到对象。根据收到的答案,它看起来像我会写低级别的 Buffer.BlockCopy code。也许使用不安全code。

OK just to be clear, I cannot have any metadata in the output file. Just the object bytes. Packed object-to-object. Based on answers received, it looks like I'll be writing low-level Buffer.BlockCopy code. Perhaps using unsafe code.

推荐答案

转换一个对象的字节数组:

Convert an object to byte array:

// Convert an object to a byte array
public static byte[] ObjectToByteArray(Object obj)
{
    BinaryFormatter bf = new BinaryFormatter();
    using (var ms = new MemoryStream())
    {
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }
}

您只需要这个功能复制到code和发送给它,你需要转换为字节数组的对象。如果你需要转换的字节数组再次对象,你可以使用下面的funcion:

You just need copy this function to your code and send to it the object that you need convert to byte array. If you need convert the byte array to object again you can use the funcion below:

// Convert a byte array to an Object
public static Object ByteArrayToObject(byte[] arrBytes)
{
    using (var memStream = new MemoryStream())
    {
        var binForm = new BinaryFormatter();
        memStream.Write(arrBytes, 0, arrBytes.Length);
        memStream.Seek(0, SeekOrigin.Begin);
        var obj = binForm.Deserialize(memStream);
        return obj;
    }
}

您可以使用此funcions使用自定义类。你只需要在你的类中添加[Serializable]属性来启用系列化

You can use this funcions with custom classes. You just need add [Serializable] attribute in your class to enable serialization

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

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