Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting protobuf-net inheritance "tree"

Going on with my quest to bend protobuf-net to my own will..

I've seen a few questions around SO on how to add sub-classes dynamically for the serializer to be able to encode the sub-class.., like this or this

My situation is bit different, I have a base class that might get sub-classed in late-bounded code, and I want to serialize is as the BASE class, and completely ignore the sub-class's fields/properties.

The reason I need this, is that later on, when I deserialize the data, the sub-class's code will not be even available, so constructing the sub-class will not be even possible.

Is there a way to limit/prohibit sub-class serializtion?

In my case I have a List where some items in the list are DerivedClass.

I would like to find a way to make protobuf-net serialize everything as BaseClass and to deserialize to BaseClass as well...

I've tried peering into code, but haven't found something too useful.

like image 704
damageboy Avatar asked Nov 04 '22 13:11

damageboy


1 Answers

Normally, the library is very particular about spotting derived classes - and treating them differently from the base class. The only current exception to that is proxy classes, in particular Entity Framework and NHibernate. For a tidy solution, it would seem practical to add some kind of "ignore subclasses" switch. But while that doesn't exist, a very lazy (and hacky) approach would be to cheat using the existing handling for NHibernate, for example:

namespace NHibernate.Proxy {
    interface INHibernateProxy {}
}
...
public class SomeDerivedType : BaseType, INHibernateProxy {}

this will then automatically be serialized as per BaseType. It does have a faint whiff of cheating about it, though.

like image 133
Marc Gravell Avatar answered Nov 09 '22 12:11

Marc Gravell