简体   繁体   English

与protobuf-net和C#的接口

[英]Interfaces with protobuf-net and C#

Does anybody know what is the right way to set up a ProtoContract for an Interface ? 有谁知道为接口设置ProtoContract的正确方法是什么?

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. 我正在使用NuGet的protobuf-net r470。

BTW: This example is from a set of "Lessons through tests" showing how to do serialization with protobuf-net for my coworkers. 顺便说一句:这个例子来自一组“通过测试的教训”,展示了如何使用protobuf-net为我的同事进行序列化。

Thanks for reading :) 谢谢阅读 :)

Interesting; 有趣; yes, it looks like something is up there. 是的,看起来有些东西在那里。 However, it does work when exposed as a member, ie 但是,它作为成员公开时确实有效,即

[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. 我将不得不查看界面支持作为对象的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM