I would like to use protobuf-net to serialize a derived class as a base class. In other words, I want the serialization process to discard any indications that the type is received:
[ProtoContract] class Base { [ProtoMember(1)] public string PublicInfo { get; set; } } class Derived : Base { public string SecretInfo { get; set; } } class Program { static void Main(string[] args) { Derived d = new Derived() { PublicInfo = "public info", SecretInfo = "secret info" }; using (var ms = new MemoryStream()) { Serializer.NonGeneric.Serialize(ms, d as Base); ms.Seek(0, SeekOrigin.Begin); Base deserialized = Serializer.Deserialize<Base>(ms); Console.WriteLine("Deserialized type: " + deserialized.GetType()); Console.WriteLine("Deserialized value: " + deserialized.PublicInfo); } Console.ReadLine(); } }
I want the above program to create
Deserialized type: Base Deserialized value: public info
but instead, I get an exception from "Type not expected."
If I add [ProtoContract]
to Derived
, the PublicInfo
field PublicInfo
not be set. And if I also add [ProtoInclude(2, typeof(Derived))]
to Base
, then the deserialized type is Derived
, not Base
, as I want.
What am I missing? Sorry if I missed the answer elsewhere. I think I'm asking for something like the opposite of this question , although I would not want to explicitly add fields through RuntimeTypeModel
.
source share