Protobuf-net serialization without annotation

后端 未结 3 1926
一个人的身影
一个人的身影 2020-12-08 01:19

I looked at this answer and I am in a situation where I don\'t need to maintain backward compatibility and I have to have a solution that works without having to decorate do

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 01:53

    InferTagFromName (and it's twin, InferTagFromNameDefault) only take a hand when it is necessary to resolve a tag number for a member; they don't influence which members need to be serialized (so currently the answer to that would be: none, even if the system knew about them). The option you might have chosen would be ImplicitFields, but that is currently only available as a [ProtoContract(...)] marker. If you don't mind a little annotation, a pragmatic fix may be:

    [ProtoContract(ImplicitFields = ImplicitFields.AllPublic)]
    

    on User, Company and Product, and something a bit more complex for BaseUser (because of the inheritance):

    [ProtoContract(ImplicitFields = ImplicitFields.AllPublic, ImplicitFirstTag = 10)]
    [ProtoInclude(1, typeof(User))]
    

    Note we haven't had to add lots of per-member annotation. If you are really really anti-attributes, then it is also possible to configure the entire model through code, via:

    RuntimeTypeModel.Default.Add(typeof(Product), false).Add("Name", "Sku");
    RuntimeTypeModel.Default.Add(typeof(Company), false).Add("Name", "Address",
             "Type", "Products");
    RuntimeTypeModel.Default.Add(typeof(User), false).Add("FirstName", "LastName",
             "Age", "BirthDate", "Friends", "Company");
    RuntimeTypeModel.Default.Add(typeof(BaseUser), false).Add(10, "SSN")
             .AddSubType(1, typeof(User));
    

提交回复
热议问题