问题
[DataContract]
public class I<TId>
{
[DataMember(Order = 1)]
public TId Id { get; set; }
}
[DataContract]
public class J : I<int>
{
[DataMember(Order = 1)]
public string Description { get; set; }
}
class Program
{
static void Main()
{
var o = new J { Id = 5, Description = "xa-xa", };
using (var ms = new MemoryStream())
{
Serializer.Serialize(ms, o);
ms.Position = 0;
var o2 = Serializer.Deserialize<J>(ms);
Debug.Assert(o.Id == o2.Id);
}
}
}
Why does the assertion fail and how to fix it?
Thanks.
回答1:
It fails because protobuf-net can't process inheritance unless you give it more of a clue either via attributes or a runtime type-model - essentially it needs to get a field number from somewhere (i.e. you). I am content to concede that maybe a trace warning might be useful in this case, since it is reasonably clear that there is probably more to this inheritance scenario than just J.
The following addition (at runtime) fixes it:
RuntimeTypeModel.Default.Add(typeof(I<int>), true).AddSubType(2, typeof(J));
(the only significance of 2 there is that it doesn't conflict with any other fields defined for I<int>).
来源:https://stackoverflow.com/questions/6285755/help-needed-with-the-most-trivial-protobuf-net-example-4