delegate void f<in T>(T p) where T : Google.Protobuf.IMessage;
// class ProtoMessageA is protobuf generated class which derived from Google.Protobuf.IMessage
void handler(ProtoMessageA m){}
f<ProtoMessageA> h = handler;
Then put it into dict, due to Dictionary<int, f<T>>
is illegal, so change value type to object:
Dictionary<int, object> d = new Dictionary<int, object>();
d[1] = h;
Now get delegate from dict and invoke it:
ProtoMessageA m;
var h = d[1];
((f<ProtoMessageA>)h).Invoke(m);
Works fine so far.
However, if message obejct is created at runtime, the specific type cannot be determined at compile time, it might be ProtoMessageA, ProtoMessageB... so use their base class IMessage to hold:
Google.Protobuf.IMessage m = descriptor.Parser.ParseFrom(bytes array);
// simplfied here, the int key can make sure get
// correct delegate instance(parameter type same as m)
var h = d[1];
((f<???>)h).Invoke(m);
If cast h
to f<Google.Protobuf.IMessage>
, it will report Specified cast is not valid
Also I can get specific type of message by
var t = m.GetType();
But t
is a variable, it can not as template argument as:
f<t>
The paradox is if not cast to the right type, Invoke cannot be call, however, the template type cannot know at compile time, it is runtime info.
Does it possible to invoke it?