I receive a message using protobuf-net. The message has 1 field with the type of the message stored in it (the field is of enum type). Now I know the message is of a type that inherit from the base type. How can I cast the object I get from the Serializer to the appriopriate type?
Definition of classes:
[ProtoContract]
class Annoucement
{
public enum msgType
{
AKCJA = 0,
CZEKAJ = 1,
GOTOWY = 2,
NOWY_GRACZ = 3,
LISTA_GRACZY = 4,
ERROR = 5,
MAPA = 6,
UPDATE = 7,
LISTAGIER = 8,
JOINGAME = 9,
QUIT = 10
}
[ProtoMember(1)]
public msgType typ;
}
[ProtoContract, ProtoInclude(14, typeof(Annoucement))]
class Update : Annoucement
{
[ProtoMember(1)]
public List<Tank> czolg;
[ProtoMember(2)]
public List<Pocisk> pocisk;
[ProtoMember(3, IsRequired = false)]
public List<Bonus> bonus;
}
How can I do something in idea similiar to this:
Annoucement ann = Serializer.DeserializeWithLengthPrefix<Annoucement> (str, PrefixStyle.Base128);
switch (ann.typ) {
case Annoucement.msgType.UPDATE:
{
Update temp = (Update)ann;
Console.WriteLine (temp.czolg.Count);
List<Tank>.Enumerator i = temp.czolg.GetEnumerator ();
Console.WriteLine (i.Current.life);
}
break;
It should just work; I believe the problem is that the attributes are inverted (I will take a note to raise a clearer error in this case) – it should be :
i.e. the base needs to know about the descendants. Not I removed the discriminator from serialization, as that is redundant if it relates directly to the object type – it handles this internally via the
ProtoIncludeand will create the correct type for you. Each type needs to know only about the direct subtypes, i.e.here A needs to know about B and D; B needs to know about C; D needs to know about E and F.
Note that a “what is this” enum is a good idea here, but there is no need for it to be a field – a virtual property without a field may be more appropriate. If I have misundersood and the message-type doesn’t relate to the object-type, then ignore me ;p
Also: public fields – don’t do it. Think of the kittens… It will work, but properties are preferred (in general, I mean; nothing to do with protobuf-net).