[英]ProtoBuf-Net error: No serializer defined for type of inner class
When using protobuf-net, I have a class Data
decorated with [ProtoContract]
attribute, which defines an inner class.使用 protobuf-net 时,我有一个用
[ProtoContract]
属性装饰的 class Data
,它定义了一个内部 class。 Members of that type should be serialized as well.该类型的成员也应该被序列化。
[ProtoContract]
public class Data {
[ProtoMember(1)]
public string Member { get; set; }
[ProtoMember(2)]
public NestedData Nested { get; set; }
public class NestedData
{
[ProtoMember(1)]
public string InnerMember { get; set; }
}
}
When I instantiate this class and try to serialize it using ProtoBuf.Serializer.Serialize(System:IO.Stream, Data)
, this raises an exception "System.InvalidOperationException: 'No serializer defined for type: MinimalExample.Data+NestedData'". When I instantiate this class and try to serialize it using
ProtoBuf.Serializer.Serialize(System:IO.Stream, Data)
, this raises an exception "System.InvalidOperationException: 'No serializer defined for type: MinimalExample.Data+NestedData'". I guess that I just have a blind spot - where is my error?我想我只是有一个盲点——我的错误在哪里? I would be rather surprised if protobuf-net had a problem with handling inner classes in general.
如果 protobuf-net 通常在处理内部类时遇到问题,我会感到相当惊讶。
I am using protobuf-net 3.0.101 on .net 5.我在 .net 5 上使用 protobuf-net 3.0.101。
You just need to annotate NestedData
with [ProtoContract]
:您只需要使用
[ProtoContract]
注释NestedData
:
[ProtoContract]
public class Data
{
[ProtoMember(1)]
public string Member { get; set; }
[ProtoMember(2)]
public NestedData Nested { get; set; }
[ProtoContract]
public class NestedData
{
[ProtoMember(1)]
public string InnerMember { get; set; }
}
}
Test:测试:
void Main()
{
var data = new Data
{
Member = "member",
Nested = new Data.NestedData
{
InnerMember = "inner"
}
};
using var mem = new MemoryStream();
ProtoBuf.Serializer.Serialize(mem, data);
mem.Position = 0;
var data2 = ProtoBuf.Serializer.Deserialize<Data>(mem);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.