Protobuf-Net as copy constructor

给你一囗甜甜゛ 提交于 2020-01-05 05:54:28

问题


is it possible to create a generic copy constructor based on protobuf-net? Something like:

   public class Person
   {
      public Int32 Id { get; set; }

      public String FirstName { get; set; }

      public Int32 Age { get; set; }

      public String Name { get; set; }
   }


   public static void DeepCopyCosntructor<T>(T source, T target)
   {
      // copy all properties by protobuf-net
   }

I want to avoid reflection, but I don't know how to fill the properties of target without recreating a new object.


回答1:


The issue to consider here is the "merge" semantics as defined by the protobuf specification. You'd be fine for basic properties, but for collections and dictionaries, the default behaviour is to add, not replace. So, you'd need to add the usual protobuf-net attributes, and make sure that every collection is set to overwrite:

[ProtoMember(n, OverwriteList = true)]

Again, I'm not sure this is the best use-case for protobuf-net, but: a merge can be done by passing in target; so with the v1 API:

using (var ms = new MemoryStream())
{
    Serializer.Serialize<T>(ms, source);
    ms.Position = 0;
    target = Serializer.Merge<T>(ms, target);
}

or in the v2 API:

using (var ms = new MemoryStream())
{
    RuntimeTypeModel.Default.Serialize(ms, source);
    ms.Position = 0;
    target = RuntimeTypeModel.Default.Deserialize(ms, target, typeof(T));
}

Note that in both cases the target = is primarily to handle the scenario where target is initially null.



来源:https://stackoverflow.com/questions/48058718/protobuf-net-as-copy-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!