如何使用protobuf-net嵌入类型信息进行序列化和反序列化?

4

我希望能够以某种方式序列化IMessage的具体实例,以便保留/嵌入类型信息(类似于例如Json.NET中可用的内容),以便在反序列化时可以使用该类型信息来生成那些具体实例。 我非常清楚下面的序列化/反序列化方法不起作用。 如何改变它们使其起作用,任何指导将不胜感激。

public interface IMessage {}
public interface IEvent : IMessage {}
[ProtoContract]
public class DogBarkedEvent : IEvent {
  [ProtoMember(0)]
  public string NameOfDog { get; set; }
  [ProtoMember(1)]
  public int Times { get; set; }
}

//Somewhere in a class far, far away
public byte[] Serialize(IMessage message) {
  using(var stream = new MemoryStream()) {
    ProtoBuf.Serializer.Serialize<IMessage>(stream, message);
    return stream.ToArray();
  }
}

public IMessage Deserialize(byte[] data) {
  using(var stream = new MemoryStream(data)) {
    return ProtoBuf.Serializer.Deserialize<IMessage>(stream);
  }
}

简单来说:序列化事件被写入持久性存储。但在读取时,使用一个带有泛型参数的反序列化方法并不可行(最好的方法就是将类型信息作为常规参数指定或使用通用合同,如此处的IMessage)。


添加了无属性建模示例 - Marc Gravell
1个回答

3
有两种方法可以处理这个问题; 我最不喜欢的选项是使用DynamicType = true - 这更昂贵,但限制了可移植性和版本控制,并且对于预先不知道数据的情况没有要求。 我更喜欢的选项是为每个接口声明一个固定标识符,使其能够识别数据本身。以下是示例。
顺便说一下,DontAskWrapper是因为Serialize()使用GetType(),这意味着它无法检测到接口基础部分。 我猜我可以改进它,但这对于今天的v2有效。
using System.Diagnostics;
using System.IO;
using NUnit.Framework;
using ProtoBuf;
using ProtoBuf.Meta;

namespace Examples.Issues
{
    [TestFixture]
    public class SO7078615
    {
        [ProtoContract] // treat the interface as a contract
        // since protobuf-net *by default* doesn't know about type metadata, need to use some clue
        [ProtoInclude(1, typeof(DogBarkedEvent))]
        // other concrete messages here; note these can also be defined at runtime - nothing *needs*
        // to use attributes
        public interface IMessage { }
        public interface IEvent : IMessage { }

        [ProtoContract] // removed (InferTagFromName = true) - since you are already qualifying your tags
        public class DogBarkedEvent : IEvent
        {
            [ProtoMember(1)] // .proto tags are 1-based; blame google ;p
            public string NameOfDog { get; set; }
            [ProtoMember(2)]
            public int Times { get; set; }
        }

        [ProtoContract]
        class DontAskWrapper
        {
            [ProtoMember(1)]
            public IMessage Message { get; set; }
        }

        [Test]
        public void RoundTripAnUnknownMessage()
        {
            IMessage msg = new DogBarkedEvent
            {
                  NameOfDog = "Woofy", Times = 5
            }, copy;
            var model = TypeModel.Create(); // could also use the default model, but
            using(var ms = new MemoryStream()) // separation makes life easy for my tests
            {
                var tmp = new DontAskWrapper {Message = msg};
                model.Serialize(ms, tmp);
                ms.Position = 0;
                string hex = Program.GetByteString(ms.ToArray());
                Debug.WriteLine(hex);

                var wrapper = (DontAskWrapper)model.Deserialize(ms, null, typeof(DontAskWrapper));
                copy = wrapper.Message;
             }
            // check the data is all there
            Assert.IsInstanceOfType(typeof(DogBarkedEvent), copy);
            var typed = (DogBarkedEvent)copy;
            var orig = (DogBarkedEvent)msg;
            Assert.AreEqual(orig.Times, typed.Times);
            Assert.AreEqual(orig.NameOfDog, typed.NameOfDog);
        }
    }
}

以下是没有属性的相同内容:

public interface IMessage { }
public interface IEvent : IMessage { }
public class DogBarkedEvent : IEvent
{
    public string NameOfDog { get; set; }
    public int Times { get; set; }
}
class DontAskWrapper
{
    public IMessage Message { get; set; }
}

[Test]
public void RoundTripAnUnknownMessage()
{
    IMessage msg = new DogBarkedEvent
    {
        NameOfDog = "Woofy",
        Times = 5
    }, copy;
    var model = TypeModel.Create();
    model.Add(typeof (DogBarkedEvent), false).Add("NameOfDog", "Times");
    model.Add(typeof (IMessage), false).AddSubType(1, typeof (DogBarkedEvent));
    model.Add(typeof (DontAskWrapper), false).Add("Message");


    using (var ms = new MemoryStream())
    {
        var tmp = new DontAskWrapper { Message = msg };
        model.Serialize(ms, tmp);
        ms.Position = 0;
        string hex = Program.GetByteString(ms.ToArray());
        Debug.WriteLine(hex);

        var wrapper = (DontAskWrapper)model.Deserialize(ms, null, typeof(DontAskWrapper));
        copy = wrapper.Message;
    }
    // check the data is all there
    Assert.IsInstanceOfType(typeof(DogBarkedEvent), copy);
    var typed = (DogBarkedEvent)copy;
    var orig = (DogBarkedEvent)msg;
    Assert.AreEqual(orig.Times, typed.Times);
    Assert.AreEqual(orig.NameOfDog, typed.NameOfDog);
}

请注意,在这两种情况下,TypeModel都应该被缓存和重复使用;它是线程安全的,因此可以被不同的线程并行地大量使用等。

我已经采用了外部化类型信息并根据需要提供给非泛型的序列化/反序列化方法的路线。我不太喜欢在与序列化关系不大的接口上放置属性(尽管我理解有时这就是事实),特别是如果它们强制我每次有新的实现者时都要重新访问它们(ProtoInclude ~= XmlInclude)。当然,使用.proto文件并生成类时,这可能会带来较少的问题。 - Yves Reynhout
@Yves 如果你愿意的话,我可以向你展示如何在没有属性的情况下完成完全相同的事情? - Marc Gravell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接