开发者

protobuf-net ignores [KnownType] and requires ProtoInclude to be added

using protobuf-net.dll 2.0.0.431

I'm attempting to serialize a class hierarchy using [DataContract] and [DataMember].

[DataContract]
[KnownType(typeof(LoginRequest))]    
public class Message
{
    [DataMember(Order = 2)]
    public int Id { get; set; }
}

[DataContract]
public class LoginRequest : Message
{
    [DataMember(Order = 1)]
    public string Username { get; set; }

    [DataMember(Order = 2)]
    public string Password { get; set; }                
}

and to serialize/deserialize:

            using (var file = File.Create(filename))
            {
                Serializer.Serialize(file, loginRequest);
            }

            LoginRequest deserialized;
            using (var file = File.OpenRead(filename))
            {
                deserialized = Serializer.Deserialize<LoginRequest>(file);
            }

            ReflectionUtils.Compare(loginRequest, deserialized);

The Id field of abstract class Message is not serialized.

To make it work I have to decorate Message with:

[ProtoInclude(1, typeof(LoginRequest))]

Why is this? I've read this similar question but Marc concl开发者_运维技巧udes that 'this is no longer required in v2 - you can specify this at runtime, or use DynamicType'

I would prefer not to specify anything extra other than KnownType


[KnownType(...)] is not enough, as the library also need a unique (for that type) integer to use as the key (the 1 in the example). Inferring it qutomatically is too risky, as it could cause unexpected breaks when tweaking the type (and version safety is a very deliberate design goal).

If you don't want to add an attribute for this, you can tell it what it needs at runtime, i.e. (in your startup code):

RuntimeTypeModel.Default[typeof(Message)]
    .AddSubType(1, typeof(LogonRequest));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜