简体   繁体   English

在 Object 上使用 BinaryWriter

[英]Using BinaryWriter on an Object

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.我的应用程序是一个小型 C# 数据库,我正在使用BinaryWriter将数据库保存到一个文件,该文件适用于 bool、uint32 等基本类型。
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 .虽然我有一个类型为Object的变量(允许用户存储任何数据类型),但是由于我的应用程序不(也不需要)知道这个变量的真实类型,我不确定如何编写它使用BinaryWriter
Is there a way I could perhaps grab the memory of the variable and save that?有没有办法我可以抓住变量的 memory 并保存它? Would that be reliable?那会可靠吗?

Edit:编辑:

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. ba_friend 提供的答案有两个函数用于将 Object 反序列化为字节数组,可以使用 BinaryWriter 连同其长度一起写入。

You can use serialization for that, especially the BinaryFormatter to get a byte[] .您可以为此使用序列化,尤其是BinaryFormatter来获取byte[]
Note : The types you are serializing must be marked as Serializable with the [Serializable] attribute.注意:您要序列化的类型必须使用[Serializable]属性标记为Serializable

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM