在一个对象使用的BinaryWriter

编程入门 行业动态 更新时间:2024-10-28 06:36:25
本文介绍了在一个对象使用的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

本文发布于:2023-05-25 00:27:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/218692.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   BinaryWriter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!