Interfaces with protobuf-net and C#

走远了吗. 提交于 2019-12-20 01:35:41

问题


Does anybody know what is the right way to set up a ProtoContract for an Interface?

I get the following exception "The type cannot be changed once a serializer has been generated" using only attributes.

Code used:

    [ProtoContract]
    public class Lesson5TestClass2 : ILesson5TestInteface1
    {
        [ProtoMember(1)]
        public string Name { get; set; }
        [ProtoMember(2)]
        public string Phone { get; set; }
    }

    [ProtoContract]
    [ProtoInclude(1000, typeof(Lesson5TestClass2))]
    public interface ILesson5TestInteface1
    {
        [ProtoMember(1)]
        string Name { get; set; }
        [ProtoMember(2)]
        string Phone { get; set; }
    }

I'm able to deserialize only if I add the following setting:

  RuntimeTypeModel.Default.Add(typeof (ILesson5TestInteface1), true)
      .AddSubType(50, typeof(Lesson5TestClass2));

I'd really love to configure this using only attributes.

I'm using protobuf-net r470 from NuGet.

BTW: This example is from a set of "Lessons through tests" showing how to do serialization with protobuf-net for my coworkers.

Thanks for reading :)


回答1:


Interesting; yes, it looks like something is up there. However, it does work when exposed as a member, i.e.

[ProtoContract]
class Wrapper
{
    [ProtoMember(1)]
    public ILesson5TestInteface1 Content { get; set; }
}
static class Program
{
    static void Main()
    {
        Wrapper obj = new Wrapper
        {
            Content = new Lesson5TestClass2()
        }, clone;
        using(var ms = new MemoryStream())
        {
            Serializer.Serialize(ms, obj);
            ms.Position = 0;
            clone = Serializer.Deserialize<Wrapper>(ms);
        }
        // here clone.Content *is* a Lesson5TestClass2 instance
    }
}

I will have to look to see what is up with interface support as the root object.



来源:https://stackoverflow.com/questions/8182188/interfaces-with-protobuf-net-and-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!