C# 和 .NET:如何使用 BinaryWriter 将结构序列化为 byte[] 数组?

发布于 2024-12-04 15:38:56 字数 1436 浏览 6 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

土豪 2024-12-11 15:38:56

使用 BinaryFormatter 将对象序列化为字节[]。 BinaryWriter 仅用于将字节写入流。

MyObject obj = new MyObject();
byte[] bytes;
IFormatter formatter = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream())
{
   formatter.Serialize(stream, obj);
   bytes = stream.ToArray();
}

Use the BinaryFormatter to serialize an object to a byte[]. BinaryWriter is just for writing bytes to a stream.

MyObject obj = new MyObject();
byte[] bytes;
IFormatter formatter = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream())
{
   formatter.Serialize(stream, obj);
   bytes = stream.ToArray();
}
世界和平 2024-12-11 15:38:56

从评论来看,OP的场景需要与应用程序/.NET的未来版本具有很强的兼容性,在这种情况下,我总是建议反对 BinaryFormatter - 它有许多“功能”,只需版本之间不能很好地工作(当然平台之间也不能很好地工作)。

我建议查看基于合约的序列化器;我有偏见,但我倾向于 protobuf-net (它映射到 Google 的 protobuf 规范)。最简单的方法是以这样的方式对类型进行属性设置,使库可以轻松地处理它们(尽管也可以在没有属性的情况下完成),例如:(

 [ProtoContract]
 public class Customer {
     [ProtoMember(1)]
     public List<Order> Orders {get {....}}

     [ProtoMember(2)]
     public string Name {get;set;}

     ... etc
 }

属性 appoach 是如果您完成了任何 XmlSerializer 或 DataContractSerializer 工作,那么非常熟悉 - 事实上,如果您不想添加 protobuf-net 特定属性,protobuf-net 可以使用这些属性)

,然后类似于:

Customer cust = ...
byte[] data;
using(var ms = new MemoryStream()) {
    Serializer.Serialize(ms, cust);
    data = ms.ToArray();
}

产生的数据way 是独立于平台的,并且可以加载到任何匹配的合约上(它甚至不需要是 Customer - 它可以是通过属性具有匹配布局的任何类型)。事实上,在大多数情况下,它可以轻松加载到任何其他 protobuf 实现中 - Java、C++ 等。

From comments, the OP's scenario requires strong compatibility with future versions of the application / .NET, in which case I always advise againt BinaryFormatter - it has many "features" that simply don't work well between versions (and certainly not between platforms).

I recommend looking at contract-based serializers; I'm biased, but I lean towards protobuf-net (which maps to Google's protobuf specification). The easiest way to do this is to attribute the types in such a way that the library can make light work of them (although it can also be done without attributes), for example:

 [ProtoContract]
 public class Customer {
     [ProtoMember(1)]
     public List<Order> Orders {get {....}}

     [ProtoMember(2)]
     public string Name {get;set;}

     ... etc
 }

(the attribute appoach is very familiar if you've done any XmlSerializer or DataContractSerializer work - and indeed protobuf-net can consume the attributes from those if you don't want to add protobuf-net specific attributes)

then something like:

Customer cust = ...
byte[] data;
using(var ms = new MemoryStream()) {
    Serializer.Serialize(ms, cust);
    data = ms.ToArray();
}

The data produced this way is platform independent, and could be loaded on any matching contract (it doesn't even need to be Customer - it could any type with matching layout via the attributes). Indeed, in most cases it'll load easily into any other protobuf implementation - Java, C++, etc.

酒绊 2024-12-11 15:38:56

代码片段。

public static byte[] XmlSerializeToByte<T>(T value) where T : class
{
    if (value == null)
    {
        throw new ArgumentNullException();
    }

    XmlSerializer serializer = new XmlSerializer(typeof(T));

    using (MemoryStream memoryStream = new MemoryStream())
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream))
        {
            serializer.Serialize(xmlWriter, value);

            return memoryStream.ToArray();
        }
    }
}

    public static T XmlDeserializeFromBytes<T> (byte[] bytes)
                                     where T : class
    {
        if (bytes == null || bytes.Length == 0)
        {
            throw new InvalidOperationException();
        }

        XmlSerializer serializer = new XmlSerializer(typeof(T));

        using (MemoryStream memoryStream = new MemoryStream(bytes))
        {
            using (XmlReader xmlReader = XmlReader.Create(memoryStream))
            {
                return (T)serializer.Deserialize(xmlReader);
            }
        }
    }


        //Serialize
        Duck duck = new Duck() { Name = "Donald Duck" };
        byte[] bytes = Test.XmlSerializeToByte(duck);
        //Deserialize
        var deDuck = Test.XmlDeserializeFromBytes<Duck>(bytes);
        Console.WriteLine(deDuck.Name);

code snippet.

public static byte[] XmlSerializeToByte<T>(T value) where T : class
{
    if (value == null)
    {
        throw new ArgumentNullException();
    }

    XmlSerializer serializer = new XmlSerializer(typeof(T));

    using (MemoryStream memoryStream = new MemoryStream())
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream))
        {
            serializer.Serialize(xmlWriter, value);

            return memoryStream.ToArray();
        }
    }
}

    public static T XmlDeserializeFromBytes<T> (byte[] bytes)
                                     where T : class
    {
        if (bytes == null || bytes.Length == 0)
        {
            throw new InvalidOperationException();
        }

        XmlSerializer serializer = new XmlSerializer(typeof(T));

        using (MemoryStream memoryStream = new MemoryStream(bytes))
        {
            using (XmlReader xmlReader = XmlReader.Create(memoryStream))
            {
                return (T)serializer.Deserialize(xmlReader);
            }
        }
    }


        //Serialize
        Duck duck = new Duck() { Name = "Donald Duck" };
        byte[] bytes = Test.XmlSerializeToByte(duck);
        //Deserialize
        var deDuck = Test.XmlDeserializeFromBytes<Duck>(bytes);
        Console.WriteLine(deDuck.Name);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文