Protobuf-Net 作为复制构造函数 [英] Protobuf-Net as copy constructor
问题描述
是否可以基于 protobuf-net 创建通用复制构造函数?类似的东西:
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.
推荐答案
这里要考虑的问题是 protobuf 规范定义的合并"语义.您可以使用基本属性,但对于集合和字典,默认行为是添加,而不是替换em>.因此,您需要添加常用的 protobuf-net 属性,并确保每个集合都设置为覆盖:
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)]
同样,我不确定这是 protobuf-net 的最佳用例,但是:可以通过传入 target
来完成合并;所以使用 v1 API:
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);
}
或在 v2 API 中:
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));
}
请注意,在这两种情况下,target =
主要是为了处理 target
最初为 null
的情况.
Note that in both cases the target =
is primarily to handle the scenario where target
is initially null
.
这篇关于Protobuf-Net 作为复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!