简体   繁体   中英

make protobuf-net serialize subclasses as the base class?

I'm using Protobuf-net (with Servicestack). I have a situation where I would like a certain class to be serialized as that exact class even if the particular instance is an inheritor. Can Protobuf-net do this? I don't care about the inheritors, nor do I ever want them sent to my client who won't have the right stuff to deserialize them.

At the moment, the answer to that would be "no". Annoyingly, it has most of the code to support that, since it works with proxy types for things like Entity Framework, NHibernate etc (which are implemented as sub-types which should be treated as the base-type), but I have not yet exposed this as an optional "ignore subtypes" feature. In theory, it should be a case of wiring things up. If your inheritance model is only a single extra level (ie the contract type is Foo , and you are giving it a SuperFoo , where SuperFoo : Foo ), then it is possible to spoof it by pretending to be NHibernate (it checks for interface/namespace names - it doesn't actually reference NHibernate itself, to reduce dependencies):

namespace NHibernate.Proxy.DynamicProxy
{
    interface IProxy { }
}
...
class SuperFoo : Foo, IProxy {...}

However! I should add:

  • this is, on consideration, something I would like to support more directly / officially
  • the above approach will slow things down slightly, as it checks for this via reflection: to do it properly , I'd want to make this "direct" (regular type-checks ets; no reflection at runtime)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM