I'm trying to create a function to automatically parse protobuf byte array and return an object no matter the type. All protobuf classes extend the IMessage
interface, so I should be able to return IMessage
type.
public IMessage Deserialize(int key, byte[] bytes)
{ ... }
In Java I just keep track of all the parsers by key and pull the right one out when needed:
public final Map<Integer, Parser<? extends Message>> parsersByKey
= new HashMap<Integer, Parser<? extends Message>> () {{
put(1, HiMessage.parser());
}};
public Message parser(int key, byte[] data) {
Parser<? extends Message> parser = parsersByKey.get(key);
Message message = parser.parseFrom(data);
return message;
}
But in C# I'm having two issues:
- I can't store a dictionary of parsers since there are no anonymous types:
IDictionary<int, IMessage<?>>
(doesn't compile). - Even if I could store in a dictionary, I'm struggling to define a
MessageParser<??> parser = ...
to do the parsing.
Since they are all the same type family (IMessage
), I should be able to do this. Each parser knows how to parse its type and using ints and keys should allow me to get the right parser.
What's the right way to get this to work? Or if it doesn't, is there a way to use generics without declaring the type?