Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interfaces with protobuf-net and C#

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 :)

like image 237
graffic Avatar asked Nov 14 '22 14:11

graffic


1 Answers

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.

like image 151
Marc Gravell Avatar answered Dec 16 '22 11:12

Marc Gravell