覆盖基于每个属性的序列化内容 [英] Overriding what's serialized on a per property basis

查看:45
本文介绍了覆盖基于每个属性的序列化内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 protobuf-net 通过网络同步两个对象,因为我能够跟踪两个同步之间所做的更改,我只能发送更改的内容而不是整个对象.

I'm using protobuf-net to sync two objects through network, as I'm able to track changes made between two sync I can only send what's changed instead of the whole object.

所以基本上我想基于脏"标志覆盖所有可为空的属性序列化.

So basically I'd like to override all nullable properties serialization based on a 'dirty' flag.

有没有好"的地方?怎么做?(我可以使用一个线程本地 bool 来修改我的属性 getter 的行为,但很好..).

Is there a "nice" way to do that? (I can live with a thread local bool that modify the behavior of my properties getter, but well..).

我断断续续地连载真实的"对象或通用 DTO 对象.但是我被困在 DTO 上,通常我想序列化 <int, object> 的 KVP,这将是属性 id 及其数据,它可以像 Dictionary< 一样复杂;string, Hashset<int>> 例如,如果您知道类型,protobuf-net 可以很好地传输,但如果它被声明为对象,则不会.

I went on and off of serializing the "real" object or a generic DTO object. But I got stucked on the DTO where typically I wanted to serializea KVPs of <int, object>, which would be the property id and its data, which can be as complexe as a Dictionary<string, Hashset<int>> for instance, which protobuf-net transports nicely if you know the type, but not if it's declared as an Object.

一些建议将不胜感激,我在网上查看,2) 如果我处理由基本类型组成的嵌套泛型集合,这似乎是一个死胡同.1) 如果我可以改变行为,就可以正常工作,但是,DTO 仍然是完美的,因为它满足了传输更改而不是完整对象"的需要......

Some advises would be appreciated, I looked on the web and 2) seems to be a dead-end if I deal with nested generic collections made of basic types. 1) could work just fine if I can alter the behavior, but still, a DTO would have been perfect because it fullfills the need to transport changes and not "full object"...

推荐答案

protobuf-net 支持标准的ShouldSerialize* 模式;所以对于属性Foo,你可以添加:

protobuf-net supports the standard ShouldSerialize* pattern; so for a property Foo, you can add:

private bool ShouldSerializeFoo() {
    return /* true to serialize, false to omit */
}

请注意,由于元编程/反射权限,在某些平台上,该方法需要是 public.另请注意,对于 nullable 属性,如果您不希望它们被序列化,您也可以简单地返回 null.

Note that on some platforms the method needs to be public, due to meta-programming / reflection permissions. Note also that for nullable properties, you can also simply return null if you don't want them to be serialized.

我不太明白你的第二个问题想做什么;你能澄清一下吗?

I don't really understand what your second question is trying to do; can you clarify?

这篇关于覆盖基于每个属性的序列化内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆