在一个对象使用的BinaryWriter [英] Using BinaryWriter on an Object

查看:148
本文介绍了在一个对象使用的BinaryWriter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序是一个小的C#数据库,我使用的BinaryWriter 保存数据库到文件,工作正常的基本类型,如布尔,UINT32等结果
虽然我有一个变量的类型为对象(允许用户存储任何数据类型),但我的应用程序没有按'T(也不需要)知道真正的这个类型的变量,我不能确定如何使用来写的BinaryWriter 。结果
是有办法我也许可以抢变量的内存并保存? ?请问这是可靠的。

My application is a small C# database, and I'm using BinaryWriter to save the database to a file which is working fine with the basic types such as bool, uint32 etc.
Although I've got a variable that is of type Object (allowing the user to store any data type), however as my application doesn't (nor needs to) know the real type of this variable, I'm unsure how to write it using BinaryWriter.
Is there a way I could perhaps grab the memory of the variable and save that? Would that be reliable?

编辑:

由ba_friend提供的答案有对于德两个函数/连载对象为一个字节数组,它可以与使用的BinaryWriter其长度一起写的。

The answer provided by ba_friend has two functions for de/serialising an Object to a byte array, which can be written along with its length using a BinaryWriter.

推荐答案

您可以使用序列为,尤其是的BinaryFormatter 获得字节[] 。结果
注意:你是序列化的类型必须标记为序列化 [Serializable接口] 属性

You can use serialization for that, especially the BinaryFormatter to get a byte[].
Note: The types you are serializing must be marked as Serializable with the [Serializable] attribute.

public static byte[] SerializeToBytes<T>(T item)
{
    var formatter = new BinaryFormatter();
    using (var stream = new MemoryStream())
    {
        formatter.Serialize(stream, item);
        stream.Seek(0, SeekOrigin.Begin);
        return stream.ToArray();
    }
}







public static object DeserializeFromBytes(byte[] bytes)
{
    var formatter = new BinaryFormatter();
    using (var stream = new MemoryStream(bytes))
    {
        return formatter.Deserialize(stream);
    }
}

这篇关于在一个对象使用的BinaryWriter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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