与protobuf-net和C#的接口 [英] Interfaces with protobuf-net and C#
问题描述
有人知道为接口设置 ProtoContract 的正确方法是什么吗?
Does anybody know what is the right way to set up a ProtoContract for an Interface?
I得到仅使用属性的以下异常 一旦生成序列化器,类型就无法更改。
I get the following exception "The type cannot be changed once a serializer has been generated" using only attributes.
使用的代码:
[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; }
}
只有添加以下设置,我才能反序列化: / p>
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.
我正在使用NuGet的protobuf-net r470。
I'm using protobuf-net r470 from NuGet.
BTW:此示例来自一组通过测试的教训,显示了操作方法为我的同事使用protobuf-net进行序列化。
BTW: This example is from a set of "Lessons through tests" showing how to do serialization with protobuf-net for my coworkers.
感谢阅读:)
推荐答案
有趣;是的,看起来好像有东西在上面。但是,当作为成员公开时,它确实起作用,即
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
}
}
我将不得不看一下接口支持如何作为 root 对象。
I will have to look to see what is up with interface support as the root object.
这篇关于与protobuf-net和C#的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!